Find Unique Elements In List Java
Chapter:
Miscellaneous
Last Updated:
07-10-2023 07:15:01 UTC
Program:
/* ............... START ............... */
// Using a Set:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class UniqueElementsInList {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
myList.add(2);
myList.add(3);
myList.add(4);
myList.add(4);
Set<Integer> uniqueSet = new HashSet<>(myList);
System.out.println("Unique elements in the list: " + uniqueSet);
}
}
// Using a LinkedHashSet (Preserving Order):
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class UniqueElementsInList {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
myList.add(2);
myList.add(3);
myList.add(4);
myList.add(4);
Set<Integer> uniqueSet = new LinkedHashSet<>(myList);
System.out.println("Unique elements in the list (preserving order): " + uniqueSet);
}
}
// Using Java Streams (Java 8 and later):
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class UniqueElementsInList {
public static void main(String[] args) {
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
myList.add(2);
myList.add(3);
myList.add(4);
myList.add(4);
List<Integer> uniqueList = myList.stream().distinct().collect(Collectors.toList());
System.out.println("Unique elements in the list: " + uniqueList);
}
}
/* ............... END ............... */
Notes:
-
In first program You can use a Set data structure to store the unique elements from the list because a Set does not allow duplicate values.
- In second program if you want to maintain the order of elements while removing duplicates, you can use a LinkedHashSet, which is an ordered version of the Set.
- In last program we have used Java streams to filter out the unique elements from a list:
- Any of these methods will give you a list or set containing only the unique elements from the original list, depending on your preference for preserving order or not.
Tags
Find unique elements in list java #How to Get Unique Values from ArrayList using Java 8? #Get unique values from ArrayList in Java