Reputation: 59
Basically HashSet
following insertion order is not preserved, but I want to display HashSet
objects in the form of preserve order in Java.
Is it possible? If yes then can you please share some ideas.
Thanks in advance
JP.
Upvotes: 1
Views: 163
Reputation: 390
Use LinkedHashSet it preserves
the order of insertion.
Set<String> set = new LinkedHashSet<String>();
for(int i = 0; i <5; i++)
{
set.add( i+"" );
}
// insertion order is 0,1,2,3,4
for(String str : set)
{
System.out.println(str);
}
//output 0,1,2,3,4
Upvotes: 0
Reputation: 36
If the order of insertion is important, maybe you should use an ArrayList.
Upvotes: 1
Reputation: 41188
For Set there is LinkedHashSet
and for Map there is LinkedHashMap
- both retain the order in which items were inserted although there is a very small performance impact.
There is also the option of TreeMap
and TreeSet
which do not retain the order in which elements were inserted but instead keeps them in a specified order (either their natural ordering or as specified by a comparator).
Upvotes: 1
Reputation: 26094
Use LinkedHashSet instead of HashSet. LinkedHashSet will maintain the insertion order.
Upvotes: 4