1、List转为Set
List<Integer> integers = new ArrayList<>(Arrays.asList(8, 9, 4, 5, 3, 2, 1, 3, 2, 5, 7, 9, 2, 4, 6));
LinkedHashSet set = new LinkedHashSet(integers);
integers.clear();
integers.addAll(set);
System.out.println(integers);
注意点:
(1)此处使用HashSet容易导致假排序,原因是Set底层基于Map,初始化大小12,存储基于hash计算存储位置,Integer类型数据返回的code默认是本身,因此造成升序的假象
2、遍历Set去重
List<Integer> list = new ArrayList<>(Arrays.asList(8, 9, 4, 5, 3, 2, 1, 3, 2, 5, 7, 9, 2, 4, 6));
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
System.out.println(" remove duplicate " + list);
3、List的contains去重
List<Integer> list = new ArrayList<>(Arrays.asList(8, 9, 4, 5, 3, 2, 1, 3, 2, 5, 7, 9, 2, 4, 6));
List tempList = new ArrayList();
for (int i = 0; i < list.size(); i++) {
if (!tempList.contains(list.get(i))) {
tempList.add(list.get(i));
}
}
System.out.println(tempList);