I have a linkedhashset from which I need to get elements in the same order they are inserted. To retrieve, am stuck getting the elements in exact insertion order.
Converting the linkedHashset to List to get by index, but am afraid converting to list would shuffle my elements changing the order
LinkedHashSet<String> personDetails = new LinkedHashSet<String>();
//persondetails => John, kennedy, Female
List<String> details = new ArrayList<>(personDetails);
String firstName = details.get(0);
String lastName = details.get(1);
String gender = details.get(2);
Converting to list is throwing off my main objective to retrieve them in insertion order in the first place, as list does not preserve the order.
Can you please suggest me an alternate or my mistake here ?
First of all, you don't need to convert the LinkedHashSet to a List in order to retrieve them according to insertion order. You can iterate over the Set with an Iterator.
For example :
Iterator<String> iter = personDetails.iterator();
String firstName = null;
if (iter.hasNext())
firstName = iter.next();
String lastName = null;
if (iter.hasNext())
lastName = iter.next();
String gender = null;
if (iter.hasNext())
gender = iter.next();
Second of all, when you create an ArrayList
with the constructor that accepts a source Collcetion
as input, the Collection
is iterated in order to add elements to the ArrayList
. The iteration order depends on the implementation of the Collection
's iterator, and in the case of LinkedHashSet
, the iteration order is the order of insertion. Therefore your List
would preserve the insertion order.
You can see this in the Javadoc :
java.util.ArrayList.ArrayList(Collection c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With