How can I get and remove the first item from the data structure?

I need to use a data structure that can -

  • preserve insertion order.
  • Don't keep duplicates.
  • And I can easily get and remove the first element from it efficiently.

Below is my code which uses LinkedList but doesn't filter out any duplicates. And it has a method removeFirst()

that gets and removes the first item in the list.

public static LinkedList<String> getData(TypeEnum types) {
    LinkedList<String> listOfPaths = new LinkedList<String>();
    String prefix = types.equals(TypeEnum.PARTIAL) ? TypeEnum.PARTIAL.value() : TypeEnum.UNPARTIAL.value();
    listOfPaths.add(prefix + LOCAL_PATH); // first element in the list is always LOCAL PATH
    for (String path : REMOTE_PATH) {
        listOfPaths.add(prefix + path);
    }
    return listOfPaths;
}

      

Below is an example of using the method getData

:

LinkedList<String> data = getData(types);
String local_path = data.removeFirst(); // this is my local path
// use local_path here

// now iterate all the remote path
for(String remotePath : data) {
    // do something with remotePath
}

      

What options do I have that will be effective? Any other data structure can do the same, avoiding duplicates. I know Set can do this, but Set has no method removeFirst

and not sure if this is the correct structure to use here. Also, can anyone provide an example.

+3


source to share


2 answers


You can use LinkedHashSet (maintains insert order). For example, first add items to this Set

one to filter out duplicates, then add all items to LinkedList

:



public static LinkedList<String> getData(TypeEnum types) {
    LinkedList<String> listOfPaths = new LinkedList<String>();
    LinkedHashSet<String> uniques = new LinkedHashSet<String>();
    String prefix = types.equals(TypeEnum.PARTIAL) ? TypeEnum.PARTIAL.value() : TypeEnum.UNPARTIAL.value();
    uniques.add(prefix + LOCAL_PATH); // first element in the list is always LOCAL PATH
    for (String path : REMOTE_PATH) {
        uniques.add(prefix + path);
    }
    listOfPaths.addAll(uniques);
    return listOfPaths;
}

      

+4


source


This answer has been corrected as per @copeg comments, thanks.

The solution might be to simply extend the method for adding the list by doing something like this:



public class MyList<E> extends LinkedList<E> {
     @Override
     public boolean add(int index, E element){
        if(this.contains(element))return false;
        return super.add(index,element);
    }

}

      

+1


source







All Articles