List去重五种方法
程序员文章站
2022-06-10 08:31:25
...
转载自 : CSDN博主「Trainer2107」的原创文章
package cn.xbao;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public abstract class DistinctList {
// 方法一:使用java8新特性stream进行List去重
public static List distinct1(List<Object> list) {
List newList = list.stream().distinct().collect(Collectors.toList());
return newList;
}
// 方法二:双重for循环去重
public static List distinct2(List<Object> list) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (i != j && list.get(i) == list.get(j)) {
list.remove(list.get(j));
}
}
}
return list;
}
// 方法三:set集合判断去重,不打乱顺序
public static List distinct3(List<Object> list) {
Set set1 = new HashSet();
List newList = new ArrayList();
for (Object obj : list) {
if (set1.add(obj)) {
newList.add(obj);
}
}
return newList;
}
// 方法四:遍历后判断赋给另一个list集合
public static List distinct4(List<Object> list) {
List<Object> newList = new ArrayList<>();
for (Object obj : list) {
if (!newList.contains(obj)) {
newList.add(obj);
}
}
return newList;
}
// 方法五:set和list转换去重
public static List distinct5(List list) {
Set set = new HashSet<>();
List newList = new ArrayList<>();
set.addAll(list);
newList.add(set);
return newList;
}
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
list.add("张飞");
list.add("刘备");
list.add("关羽");
list.add("刘备");
System.out.println(list);
List list1 = distinct1(list);
System.out.println("java8新特性后的去重:" + list1);
List list2 = distinct2(list);
System.out.println("双重for循环去重:" + list2);
List list3 = distinct3(list);
System.out.println("set集合判断去重:" + list3);
List list4 = distinct4(list);
System.out.println("赋值新list去重:" + list4);
List list5 = distinct5(list);
System.out.println("set和list转换去重:"+ list5);
}
}
=>运行结果 :
版权声明:本文为CSDN博主「Trainer2107」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Trainer2107/article/details/78571619