Does List maintain insertion order in Java

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.

Example 1:

Java




// Java program to Maintain Insertion Order While
// Getting Unique Values from ArrayList
import java.util.*;
class GFG {
public static void main[String[] args]
{
// Creating an arrayList
ArrayList arrayList = new ArrayList[];
// adding elements to arrayList
arrayList.add[100];
arrayList.add[200];
arrayList.add[100];
arrayList.add[500];
arrayList.add[200];
arrayList.add[300];
arrayList.add[200];
arrayList.add[600];
// creating an LinkedHashSet and
// adding arrayList elements to linkedHashSet
LinkedHashSet set
= new LinkedHashSet[arrayList];
System.out.println[
"Unique values in inserted order"];
System.out.println[set];
}
}
Output Unique values in inserted order [100, 200, 500, 300, 600]

Example 2:

  • 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.
Java




// Java program to Maintain Insertion Order While
// Getting Unique Values from ArrayList
import java.util.*;
class friendsDetail {
// class field
private String name;
private String nickName;
// parameterised constructor
public friendsDetail[String name, String nickName]
{
this.name = name;
this.nickName = nickName;
}
// getter for name
public String getName[] { return name; }
// setter for name
public void setName[String name] { this.name = name; }
// getter for nickname
public String getnickName[] { return nickName; }
// setter for nickname
public void setNickName[int id]
{
this.nickName = nickName;
}
@Override public boolean equals[Object o]
{
if [this == o]
return true;
if [![o instanceof friendsDetail]]
return false;
friendsDetail that = [friendsDetail]o;
return Objects.equals[getName[], that.getName[]]
&& Objects.equals[nickName, that.nickName];
}
@Override public int hashCode[]
{
return Objects.hash[getName[], nickName];
}
// overriding toString method
public String toString[]
{
// return super.toString[];
return "[" + this.getName[] + ":"
+ this.getnickName[] + "]";
}
}
class GFG {
public static void main[String[] args]
{
ArrayList originalArrayList
= new ArrayList[];
System.out.println["Our ArrayList\n"];
originalArrayList.add[
new friendsDetail["Raushan", "Chamgader"]];
originalArrayList.add[
new friendsDetail["Yashdeep", "Dopa"]];
originalArrayList.add[
new friendsDetail["Shishya", "Gorilla"]];
originalArrayList.add[
new friendsDetail["Sonika", "Chipkali"]];
originalArrayList.add[
new friendsDetail["Himanshu", "Lalten"]];
originalArrayList.add[
new friendsDetail["Sarthak", "Nagin"]];
originalArrayList.add[
new friendsDetail["Tsering", "Battak"]];
originalArrayList.add[
new friendsDetail["Abhishek", "Liquid"]];
originalArrayList.add[
new friendsDetail["Shishya", "Gorilla"]];
originalArrayList.add[
new friendsDetail["Suraj", "Bhindi"]];
originalArrayList.add[
new friendsDetail["Sonika", "Chipkali"]];
originalArrayList.add[
new friendsDetail["Himanshu", "Lalten"]];
originalArrayList.add[
new friendsDetail["Sarthak", "Nagin"]];
// Displaying output using enhanced for loop
for [friendsDetail friend : originalArrayList] {
System.out.println[friend];
}
LinkedHashSet linkedHashSet
= new LinkedHashSet[originalArrayList];
System.out.println[
"\nUnique elements in inserted order\n"];
// Displaying output using enhanced for loop
for [friendsDetail friend : linkedHashSet] {
System.out.println[friend];
}
}
}
Output 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]




Article Tags :
Java
Java Programs
Technical Scripter
Java-ArrayList
Java-Collections
Technical Scripter 2020
Practice Tags :
Java
Java-Collections
Read Full Article

Does list maintain insertion order?

List Vs Set. 1] List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list. Set is an unordered collection, it doesn't maintain any order.

Does list maintain insertion order?

List Vs Set. 1] List is an ordered collection it maintains the insertion order, which means upon displaying the list content it will display the elements in the same order in which they got inserted into the list. Set is an unordered collection, it doesn't maintain any order.

List vs Set in Java

here are few note-worthy differences between List and Set in Java. Remember that both of them are used to store objects and provides a convenient API to insert, remove and retrieve elements, along with to support Iteration over collection.


1] Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows duplicates while Set doesn't allow any duplicate. If you insert a duplicate in Set it will replace the older value. Any implementation of Set in Java will only contain unique elements.

2] Another significant difference between List and Set in Java is order. List is an Ordered Collection while Set is an unordered collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn't maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.

3] Set uses equals[] method to check uniqueness of elements stored in Set, while SortedSet uses compareTo[] method to implement natural sorting order of elements. In order for an element to behave properly in Set and SortedSet, equals and compareTo must be consistent to each other.

4] Popular implementation of List interface in Java includes ArrayList, Vector, and LinkedList. While popular implementation of theSet interface includes HashSet, TreeSet, and LinkedHashSet.

When to use List and Set in Java?

Another good follow-up question is "when do you use List and Set in Java" , which can also be answered based on properties of List and Set we have learned here.

These difference between Set and List also teaches us when to use Set and when to prefer List. it's pretty clear that if you need to maintain insertion order or object and you collection can contain duplicates than List is a way to go.

On the other hand if your requirement is to maintain unique collection without any duplicates then Set is the way to go.

Important point to note is that both List and Set are derived from Collection Interface. In short main difference between List and Set in Java is that List is an ordered collection which allows duplicates while Set is an unordered collection which doesn't allow duplicates.


Other Java interview questions you may like
Difference between LinkedList and ArrayList in Java
Difference between ArrayList and Vector in Java
Difference between throw and throws in Java
Difference between transient and volatile variable in Java
Difference between instance and local variable in Java
Difference between start and run method of Thread

Quick Answer: Does ArrayList Maintain Order?

Feb 17 2022

▲ 7 ▼
Answer The Question

Similar Questions

  1. Is ArrayList ordered collectio
  2. Which collection is faster in Jav
  3. Is ArrayList thread saf
  4. Does list maintain insertion order pytho
  5. Is linked list faster than ArrayLis
  6. Does priority queue maintain insertion orde
  7. How can we remove an object from ArrayLis
  8. Which is better linked list or ArrayLis
  9. Does linked list allow duplicate
  10. Does Java array maintain orde
  11. Does list maintain insertion orde
  12. Which list maintains insertion order in Jav
  13. Do lists maintain order Jav
  14. Does HashMap maintain insertion orde
  15. How ArrayList increases its siz
  16. What is use of linked list over ArrayLis
  17. Does Vector maintain insertion orde
  18. What is the time complexity of ArrayList and linked lis
Asked By: Antonio Thompson Date: created: Jul 15 2021

Video liên quan

Bài mới nhất

Chủ Đề