开车—-》》》
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | package com.example.demo; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import java.util.stream.Collectors; import static java.util.Comparator.comparingLong; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toCollection; /** * List字符串去重 、 List对象去重 * Created by wosha on 2019/2/17. */ public class testDomo { /*list去重 * JDK8测试*/ @Test public void ListClear(){ List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(1); list.add(5); /* HashSet 有效 */ /*List<Integer> newList = new ArrayList<>(); HashSet hashSet = new HashSet(list); hashSet.addAll(list); newList.addAll(hashSet);*/ /* HashSet 不改变顺序 */ /*List<Integer> newList = new ArrayList<>(); HashSet hashSet = new HashSet(); for (Integer a:list){ if(hashSet.add(a)){ newList.add(a); } }*/ /* HashSet 缩减 */ /*List<Integer> newList=new ArrayList<>(new HashSet(list));*/ /* 新方式:Stream流操作 */ List<Integer> newList = list.stream().distinct().collect(Collectors.toList()); for (Integer a:newList){ System.out.println(a); } } /*list实体对象去重 * JDK8测试*/ @Test public void ListBeanClear(){ List<TestBean> list = new ArrayList<>(); TestBean testBean1 = new TestBean(1,"张三","男"); TestBean testBean2 = new TestBean(2,"李四","男"); TestBean testBean3 = new TestBean(3,"王五","女"); TestBean testBean4 = new TestBean(3,"赵六","男"); TestBean testBean5 = new TestBean(2,"冯七","男"); list.add(testBean1); list.add(testBean2); list.add(testBean3); list.add(testBean4); list.add(testBean5); /* 新方式: Stream流操作 */ List<TestBean> newList = list.stream().collect( //对Int类型做处理 collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(TestBean::getId))), ArrayList::new) //对String类型做处理 //collectingAndThen(toCollection(() -> new TreeSet<>(comparing(TestBean::getSex))), ArrayList::new) ); for (TestBean a:newList){ System.out.println(a); } } } |
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | package com.example.demo; /** * 测试实体 * Created by wosha on 2019/2/17. */ public class TestBean { private Integer id; private String name; private String sex; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } @Override public String toString() { return "TestBean{" + "id='" + id + '\'' + ",name='" + name + '\'' + ", sex='" + sex + '\'' + '}'; } public TestBean(Integer id,String name, String sex) { this.id = id; this.name = name; this.sex = sex; } } |