I have a linkedhashset which gets a person details - firstName, lastName and gender. Using a linkedHashset to get the elements in insertion order.
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);
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 :
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.