List的五种去重方式
一、String去重:
//set集合去重,不改变原有的顺序 public static void pastLeep1(List<String> list){ System.out.println("list = [" + list.toString() + "]"); List<String> listNew=new ArrayList<>(); Set set=new HashSet(); for (String str:list) { if(set.add(str)){ listNew.add(str); } } System.out.println("listNew = [" + listNew.toString() + "]"); } //遍历后判断赋给另一个list集合 public static void pastLeep2(List<String> list){ System.out.println("list = [" + list.toString() + "]"); List<String> listNew=new ArrayList<>(); for (String str:list) { if(!listNew.contains(str)){ listNew.add(str); } } System.out.println("listNew = [" + listNew.toString() + "]"); } //set去重 public static void pastLeep3(List<String> list){ System.out.println("list = [" + list + "]"); Set set = new HashSet(); List<String> listNew=new ArrayList<>(); set.addAll(list); listNew.addAll(set); System.out.println("listNew = [" + listNew + "]"); } //set去重(缩减为一行) public static void pastLeep4(List<String> list){ System.out.println("list = [" + list + "]"); List<String> listNew=new ArrayList<>(new HashSet(list)); System.out.println("listNew = [" + listNew + "]"); } //去重并按自然顺序排序 public static void pastLeep5(List<String> list){ System.out.println("list = [" + list + "]"); List<String> listNew=new ArrayList<>(new TreeSet<String>(list)); System.out.println("listNew = [" + listNew + "]"); }
二、对象去重方法:
package com.hcycom.iams.ncolog; import java.util.*; import static java.util.Comparator.comparingLong; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toCollection; public class Test { public static void main(String[] args) { Data data1 = new Data(1,"aaaa"); Data data2 = new Data(2,"dddd"); Data data3 = new Data(1,"vvvv"); Data data4 = new Data(4,"rrrr"); Data data5 = new Data(1,"ssss"); List<Data> list = Arrays.asList(data1,data2,data3,data4,data5); List<Data> l = test2(list); System.out.println(Arrays.toString(l.toArray())); } //对象去重 public static List<Data> test2(List<Data> list){ List<Data> unique = list.stream().collect( collectingAndThen( toCollection(() -> new TreeSet<>(comparingLong(Data::getId))), ArrayList::new) ); return unique; } } // 实体对象 class Data{ private int id; private String name; public Data(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Data{" + "id=" + id + ", name='" + name + '\'' + '}'; } }