Java Remove Duplicates From List
This post provides examples, showing how to remove duplicate items from an ArrayList in Java.
Remove Duplicate Strings From ArrayList
Since a Set
cannot hold duplicate elements, we can instantiate a Set
object passing in the ArrayList with duplicates as a parameter.
For example:
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicatesFromArrayList {
public static void main(String[] args) {
ArrayList<String> pets = new ArrayList<>();
pets.add("cat");
pets.add("dog");
pets.add("cat");
pets.add("hamster");
System.out.println(pets);
Set<String> hashSet = new LinkedHashSet(pets);
ArrayList<String> removedDuplicates = new ArrayList(hashSet);
System.out.println(removedDuplicates);
}
}
Output:
[cat, dog, cat, hamster]
[cat, dog, hamster]
- How to compare two ArrayLists in Java
- How to loop through an ArrayList in Java
- How to convert list to array in Java
Remove Duplicate Integers From List
Likewise, we can use the same methodology to remove duplicate integers.
import java.util.*;
public class RemoveDuplicatesFromArrayList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,2,2,3,5);
System.out.println(numbers);
Set<Integer> hashSet = new LinkedHashSet(numbers);
ArrayList<Integer> removedDuplicates = new ArrayList(hashSet);
System.out.println(removedDuplicates);
}
}
Output:
[1, 2, 2, 2, 3, 5]
[1, 2, 3, 5]
Remove Duplicates From List Using Java 8 Lambdas
import java.util.*;
import java.util.stream.Collectors;
public class RemoveDuplicatesFromArrayList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,2,2,3,5);
System.out.println(numbers);
List<Integer> removedDuplicates = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(removedDuplicates);
}
}
Output:
[1, 2, 2, 2, 3, 5]
[1, 2, 3, 5]