Question

I am creating RDF statements in Java. I have two HashSets and would like to add both of them into a TreeSet for example. Here is my code:

Collection<Statement> model = new HashSet<Statement>();
Collection<Statement> model_1 = new HashSet<Statement>();
Collection<Statement> treeSet = new TreeSet<Statement>();

After storing some statements into these two Hashsets, I added both of them in the TreeSet: Here is the code:

treeSet.addAll(model);
treeSet.addAll(model_1);
for (Statement _state : treeSet)
     System.out.println(_state);

I thought that the first Hashset "model" would be added into the TreeSet and then the second Hashset "model_1" respectively. It seems that they are not ordered when I loop through the TreeSet. Could anyone please help me how to order the elements of the TreeSet in a way that I can add the first HashSet and then the second one as they are respectively.

Was it helpful?

Solution

The TreeSet will order on the elements you put in, not the order in which you put them in. A simple List may suffice here if you don't need the hashing capability, or perhaps a LinkedHashSet (which maintains insertion order whilst iterating)

Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top