<meta charset="utf-8">
传统的方法:
1. 循环list中的所有元素然后删除重复
public static List removeDuplicate(List list) { for ( int i = 0 ; i < list.size() - 1 ; i ++ ) { for ( int j = list.size() - 1 ; j > i; j -- ) { if (list.get(j).equals(list.get(i))) { list.remove(j); } } } return list; }
2. 通过HashSet踢除重复元素
public static List removeDuplicate(List list) { HashSet h = new HashSet(list); list.clear(); list.addAll(h); return list; }
- 删除ArrayList中重复元素,保持顺序
// 删除ArrayList中重复元素,保持顺序 public static void removeDuplicateWithOrder(List list) { 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); }
4.把list里的对象遍历一遍,用list.contain(),如果不存在就放入到另外一个list集合中
public static List removeDuplicate(List list){ List listTemp = new ArrayList(); for(int i=0;i<list.size();i++){ if(!listTemp.contains(list.get(i))){ listTemp.add(list.get(i)); } } return listTemp; }
5.JDK8新特性
list = list.stream().distinct().collect(Collectors.toList());
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("A");
list.add("B");
list.add("D");
list.add("E");
list.add("A");
list = list.stream().distinct().collect(Collectors.toList());
for (String s : list) {
System.out.println(s);
}
}
输出结果:
image.png
网友评论