//Stream 去重:list.stream().distinct()
public static List removeDuplicate(List list) {
HashSet hashSet = new HashSet(list);
list.clear();
list.addAll(hashSet);
return list;
}
//通过 HashSet 剔除重复元素
public static List removeDuplicate(List list) {
List newList = (List) list.stream().distinct().collect(Collectors.toList());
return newList;
}
//通过HashSet剔除重复元素
public static List removeDuplicate(List list) {
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Object next = iter.next();
if (set.add(next)) {
newList.add(next);
}
}
list.clear();
list.addAll(newList);
return list;
}
//遍历 list,用 tempList.contain()
public static List removeDuplicate(List list) {
List tempList = new ArrayList();
for (int i = 0; i < list.size(); i++) {
if (!tempList.contains(list.get(i))) {
tempList.add(list.get(i));
}
}
return tempList;
}
//循环 list 中的所有元素然后删除重复
public static List removeDuplicate(List list) {
for (int i = 0; i < list.size(); i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(i).equals(list.get(j))) {
list.remove(list.get(i));
}
}
}
return list;
}
Java中List去重的多种方法
期待奔跑2023-11-02 11:33