Rk Reddy Bairi Rk Reddy Bairi - 2 months ago 14
Java Question

Retrieve LinkedHashSet elements in the insertion order and save them to local variables

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);

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 ? Thanks.


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.