How to Maintain Insertion Order While Getting Unique Values from ArrayList in Java?
ArrayList is a part of collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. This class is found in java.util package.
If we want to maintain the insertion order of the elements, we are supposed to use LinkedHashSet. LinkedHashSet maintains the order in which the elements are inserted.
Unique values in inserted order [100, 200, 500, 300, 600]
- In this example, instead of using a wrapper class, we will use a user-defined class and will maintain insertion order while getting unique values from ArrayList.
- Since we are using a user-defined class so we are supposed to override the hashCode method and equals method so that our LinkedHashSet will be able to identify similar elements otherwise our LinkedHashSet will consider every element as a unique element.
Our ArrayList (Raushan:Chamgader) (Yashdeep:Dopa) (Shishya:Gorilla) (Sonika:Chipkali) (Himanshu:Lalten) (Sarthak:Nagin) (Tsering:Battak) (Abhishek:Liquid) (Shishya:Gorilla) (Suraj:Bhindi) (Sonika:Chipkali) (Himanshu:Lalten) (Sarthak:Nagin) Unique elements in inserted order (Raushan:Chamgader) (Yashdeep:Dopa) (Shishya:Gorilla) (Sonika:Chipkali) (Himanshu:Lalten) (Sarthak:Nagin) (Tsering:Battak) (Abhishek:Liquid) (Suraj:Bhindi)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.