Remove Duplicates from a Java List
Removing duplicates from a Java List can be achieved by utilizing various techniques. This process involves identifying and eliminating duplicate elements, resulting in a list with unique values.
The code examples below show how to remove duplicate elements from a List in Java. These examples illustrate different techniques that can be used to achieve this task:
Example 1:
List<String> list = Arrays.asList("Apple@example.com", "apple@example.com", "tello@example.com", "bello@example.com"); List<String> uniqueList = list.stream().map(String::toLowerCase) .distinct().collect(Collectors.toList()); System.out.println("Unique list: " + uniqueList);
Ouput:
Unique list: [apple@example.com, tello@example.com, bello@example.com]
Example 2:
List<String> list = Arrays.asList("Apple@example.com", "apple@example.com", "tello@example.com", "bello@example.com"); ListIterator<String> iterator = list.listIterator(); while (iterator.hasNext()) { iterator.set(iterator.next().toLowerCase()); } Set<String> newSet = new HashSet<>(list); List<String> uniqueList = new ArrayList<>(); uniqueList.addAll(newSet); System.out.println("Unique list: " + uniqueList);
Output:
Unique list: [bello@example.com, tello@example.com, apple@example.com]