List集合去重的几种方式
1. 通过set集合的特性,集合元素的唯一性
public static List heavyListMethod01(List list){
Set set=new HashSet(list);
//Set set1=new TreeSet(list);
List alist=new ArrayList();
for (Object o:set) {
alist.add(o);
}
return alist;
}
1.1利用set集合的特性,元素的唯一性 addAll(Collection c)
public static List heavyListMethod02(List list){
List newList=new ArrayList();
newList.addAll(new HashSet(list));
return newList;
}
2.通过list的方法contains方法去重
public static List heavyListMethod03(List list){
List alist=new ArrayList();
for (Object o:list) {
if(!(alist.contains(o))){
alist.add(o);
}
}
return alist;
}
3.通过遍历然后用remove方法进行去掉重复的元素
public static List heavyListMethod04(List<Object> list){
for (int i=0;i<list.size()-1;i++){
Object o =list.get(i);
for (int j=i+1;j<list.size();j++){
if(o.equals(list.get(j))){
list.remove(j);
j--;
}
}
}
return list;
}
4.(jdk1.8)调用stream方法将list转换为流,通过distinct(内部根据equals()方法)去掉流中重复的元素.
public static List heavyListMethod05(List<Object> list){
list = list.stream().distinct().collect(Collectors.toList());
return list;
}
1
2
3
4
测试验证
public static void main(String[] args) {
List list=new ArrayList();
list.add(1);
list.add(2);
list.add(5);
list.add(2);
list.add(3);
list.add(1);
list.add(4);
List list1 =heavyListMethod01(list);
System.out.println("1----"+list1);//[1, 2, 3, 4, 5]
List list2 =heavyListMethod02(list);
System.out.println("2----"+list2);//[1, 2, 3, 4, 5]
List list3 =heavyListMethod03(list);
System.out.println("3----"+list3);//[1, 2, 5, 3, 4]
List list4 =heavyListMethod04(list);
System.out.println("4----"+list4);//[1, 2, 5, 3, 4]
List list5 =heavyListMethod05(list);
System.out.println("5----"+list5);//[1, 2, 5, 3, 4]
}
|
|