如何使用 Java 删除 ArrayList 中的重复元素 (How to Remove Duplicates from ArrayList in Java)
Given an ArrayList with duplicate values, the task is to remove the duplicate values from this ArrayList in Java.
import java.util.*;
import java.util.stream.Collectors;
/**
* RemoveDuplicateElements class
* How to Remove Duplicates from ArrayList in Java
* Given an ArrayList with duplicate values, the task is to remove the duplicate values from this ArrayList in Java.
* https://www.geeksforgeeks.org/how-to-remove-duplicates-from-arraylist-in-java/
*
* @author libin
* @date 2019/3/7 14:51
*/
public class RemoveDuplicateElements {
public static void main(String[] args) {
System.out.println("采用迭代去重: ");
List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5));
System.out.println("去重前: " + list);
System.out.println("去重后: " + removeDuplicateElements(list));
System.out.println("\n采用Set去重: ");
List<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5));
System.out.println("去重前: " + arrayList);
System.out.println("去重后: " + removeDuplicateElementsBySet(arrayList));
System.out.println("\n采用Java 8 Stream.distinct()去重: ");
List<Integer> Java8List = new ArrayList<Integer>(Arrays.asList(1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5));
System.out.println("去重前: " + Java8List);
List<Integer> resultList = Java8List.stream().distinct().collect(Collectors.toList());
System.out.println("去重后: " + resultList);
}
// 采用迭代去重
public static <T> List<T> removeDuplicateElements(List<T> list) {
List<T> resultList = new ArrayList<T>();
for (T t : list) {
if (!resultList.contains(t)) {
resultList.add(t);
}
}
return resultList;
}
// 采用Set去重
public static <T> List<T> removeDuplicateElementsBySet(List<T> list) {
Set<T> set = new LinkedHashSet<T>();
set.addAll(list);
list.clear();
list.addAll(set);
return list;
}
}
点击查看结果
采用迭代去重:
去重前: [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5]
去重后: [1, 10, 2, 3, 4, 5]
采用Set去重:
去重前: [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5]
去重后: [1, 10, 2, 3, 4, 5]
采用Java 8 Stream.distinct()去重:
去重前: [1, 10, 2, 2, 10, 3, 3, 3, 4, 5, 5]
去重后: [1, 10, 2, 3, 4, 5]
Process finished with exit code 0
参考链接