Remove Duplicates from Java List
There are several ways to remove duplicates data from a list in Java. Some are as follows:
In Java 8:
List<String> list = Arrays.asList("[email protected]", "[email protected]",
"[email protected]", "[email protected]");
List<String> newList = list.stream().map(String::toLowerCase)
.distinct().collect(Collectors.toList());
System.out.println("New list without duplicates: " + newList);
The above code will give the following output:
Prior to Java 8:
List<String> list = Arrays.asList("[email protected]", "[email protected]",
"[email protected]", "[email protected]");
ListIterator<String> iterator = list.listIterator();
while (iterator.hasNext()) {
iterator.set(iterator.next().toLowerCase());
}
Set<String> newSet = new HashSet<>(list);
List<String> newList = new ArrayList<>();
newList.addAll(newSet);
System.out.println("New list without duplicates: " + newList);
The above code will give the following output: