Search code examples
javalinkedhashset

Java LinkedHashSet remove some elements from the end


I am working on a problem where i'm required to store elements with requirements of No Duplication and Maintaining order. I chose to go with LinkedHashSet Since it fulfilled both my requirements.

Let's say I have this code:

 LinkedHashSet hs = new LinkedHashSet();
  hs.add("B");
  hs.add("A");
  hs.add("D");
  hs.add("E");
  hs.add("C");
  hs.add("F");
  if(hs.contains("D")){
       //do something to remove elements added after"D" i-e remove "E", "C" and "F"
       //maybe hs.removeAll(Collection<?>c) ??
   }

Can anyone please guide me with the logic to remove these elements?

Am I using the wrong datastructure? If so, then what would be a better alternative?


Solution

  • So, after trying a couple of things mentioned above, I chose to implement a different Data structure. Since I did not have any issue with the O(n) for this problem (as my data is very small)

    I used Graphs, this library came in really handy: http://jgrapht.org/

    What I am doing is adding all elements as vertices to a DirectedGraph also creating edges between them (edges helped me solve another non-related problem as well). And when it's time to remove the elements I use a recursive function with the following pseudo code:

    removeElements(element) {
    
    tempEdge = graph.getOutgoingEdgeFrom(element)
    if(tempEdge !=null)
       return;
    tempVertex = graph.getTargetVertex(tempEdge)
    removeElements(tempVertex)
    graph.remove(tempVertex)
    
    }
    

    I agree that graph DS is not good for these kind of problems, but under my conditions, this works perfectly... Cheers!