Java 8 API添加了一个新的抽象称为流Stream,可让你以一种声明的方式处理数据。java
Stream 使用一种相似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。程序员
Stream API能够极大提升Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。数据库
这种风格将要处理的元素集合看做一种流, 流在管道中传输, 而且能够在管道的节点上进行处理, 好比筛选, 排序,聚合等。网络
元素流在管道中通过中间操做(intermediate operation)的处理,最后由最终操做(terminal operation)获得前面处理的结果。ide
(以上高大上的名词解释内容来自网络,楼主一脸懵B...总之一句话,集合间的去重操做,在java8的流式操做中,变得很优雅,/花鸡)this
好比有如下类:spa
1 Class Person{ 2 private int id; 3 private String name;
4 public Person(){} 5 public Person(int id, String name){ 6 this.id=id; 7 this.name = name; 8 } 9 }
而后有如下俩集合:code
1 List<Person> listA = new ArrayList<>(); 2 List<Person> listB = new ArrayList<>();
3 listA.add(new Person(1,"aa")); 4 listA.add(new Person(1,"bb")); 5 listA.add(new Person(1,"cc")); 6 listA.add(new Person(1,"dd")); 7 8 listB.add(new Person(1,"aa")); 9 listB.add(new Person(1,"bb")); 10 listB.add(new Person(1,"cc"));
如今但愿集合listA与listB之间发生点事,擦出点火花,好比标题上说的求交集(listA ∩ ListB)、求并集(listA ∪ listB)、求差集(listA - listB)。对象
因为两集合里保存的是对象信息,它们在进行如上操做时,要有比较判断依据,好比,id值和姓名值相同的状况下,认为俩个集合保存的是相同的对象数据。blog
此时,咱们须要先重写Person类的equals方法,以下:
Class Person{ private int id; private String name;
public Person(){} public Person(int id, String name){ this.id=id; this.name = name; } @override public boolean equals(Object obj){ if(this == obj){ return true; } if(obj == null){ return false; } if(getClass() != obj.getClass()){ return false; } Person other = (Person) obj; if(id != other.id){ return false; } if(name == null){ if(other.name != null){ return false; } }else if(!name.equals(other.name)){ return false; } return true; } }
最后,优雅地写出集合listA与listB之间发生的那些事吧。
交集(listA ∩ ListB):
List<Person> listC = listA.stream().filter(item -> listB.contains(item)).collect(Collectors.toList());
listC中的元素有:属性name值为 aa, bb, cc 的对象。
并集(listA ∪ listB):
//先合体 listA.addAll(listB); //再去重 List<Person> listC = listA.stream().distinct().collect(Collectors.toList());
listC中的元素有:属性name值为 aa, bb, cc ,dd的对象。
差集(listA - listB):
List<Person> listC = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());
listC中的元素有:属性name值为 dd的对象。
火花擦完了, that's all.......