How do I get and remove the first element of a data structure?

advertisements

I need to use a data structure which can -

  • maintain the insertion order.
  • do not store any duplicates.
  • And I can easily get and remove first element from it efficiently.

Below is my code which uses LinkedList but it doesn't filter out any duplicates. And it has removeFirst() method which gets and remove the first element in a 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 how I am using getData method:

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 are the options I have here which will be efficient? Does any other data structure can do the same thing by avoiding the duplicates. I know Set can do that, but Set doesn't have any removeFirst method and not sure whether it's a right structure to use here. Also, Can anyone provide an example as well.


You can make use of a LinkedHashSet (maintains insertion order). For instance, add the items first to this Set to filter out duplicates, then add all the items into the 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;
}