user1950349
user1950349

Reputation: 5146

Data Structure which can maintain insertion order, filter out duplicate elements and easily remove first element?

I need to use a data structure which can maintain the insertion order, do not store any duplicates and I can easily remove first element from it efficiently.

public static LinkedHashSet<String> getData(TypeEnum flowType) {
    LinkedHashSet<String> listOfPaths = new LinkedHashSet<String>();
    String prefix = flowType.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;
}

Earlier, I was using LinkedList from which I can easily remove the first element by using removeFirst() method and it also maintains the insertion order but it can store duplicate elements which is I don't want.

Can I easily get the first element by removing it from LinkedHashSet with my above solution?

What are the options I can have here which will be efficient?

Below is how I was using when getData method returns LinkedList but it doesn't filter out duplicates.

LinkedList<String> data = getData(flowType);

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
}

Upvotes: 2

Views: 1115

Answers (1)

shruti1810
shruti1810

Reputation: 4037

You can get the first element using iterator, and remove it.

    String localpath = null;
    Iterator itr = listOfPaths.iterator(); 
    if(itr.hasNext()){
      localpath = itr.next()
      listOfPaths.remove(localpath);
    }

Upvotes: 1

Related Questions