使用HashSet/TreetSet

图:使用HashSet/、java8新特性st 的流程。

1
2
3
4
5
6
7
8
9
 public static List removeDuplicationByHashSet(List<Integer> list) {
Set set = new HashSet(list); //无序===
// Set set = new TreeSet(list); //有序===

list.clear(); //把List集合所有元素清空
list.addAll(set); //把HashSet对象添加至List集合

return list;
}

java8新特性stream实现List去重(有序)

图:使用HashSet/、java8新特性st 的流程。

public static List removeDuplicationByStream(List<Integer> list) {
    List newList = list.stream().distinct().collect(Collectors.toList());
    return newList;
}

使用List集合contains方法循环遍历(有序)

public static List removeDuplicationByContains(List<Integer> list) {
    List<Integer> newList =new ArrayList<>();
    
    for (int i=0;i<list.size();i++)
    {
        if(!newList.contains(list.get(i))){
            newList.add(list.get(i));
        }
    }
    
    list.clear();
    list.addAll(newList);
    return list;
}