Java8stream处理List交集差集去重等
Java8的新特性——Stream常用于处理集合,它不会改变集合原有的结构,优点是Stream的代码会比用for循环处理简洁不少
本文主要说的是:获取两个List集合的 交集 、差集 、去重 以及list.stream()构造方法 一、两个集合的交集
例如:找出两个班 名字相同的学生 public class Student { private String studentNo; //名字 private String studentName; public Student(String studentNo, String studentName) { this.studentNo = studentNo; this.studentName = studentName; } //对象的比较涉及到equals()的重写, 这里仅仅比较studentName是否相同 @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Student)) return false; Student student = (Student) o; return studentName.equals(student.getStudentName()); } // set()和get()方法均省略.. }
学生是个对象实例,我们要比较的是名字是否相同,仅需要重写equals()方法即可 找交集@Test public void test(){ // 1班的学生 List class01=new ArrayList<>(); class01.add(new Student("1","小明")); class01.add(new Student("2","赵铁柱")); // 2班的学生 List class02=new ArrayList<>(); class02.add(new Student("1","赵铁柱")); // 找两个班名字相同的同学(取交集),比较用的是重写的equals() List sameName=class01.stream().filter(class02::contains).collect(Collectors.toList()); sameName.stream().forEach(student->System.out.println(student.getStudentName()+" ")); //output : 赵铁柱 }
需要注意的是: class01.stream().filter(class02::contains) 的filter() 会 保留 符合表达式的结果,这里面表达式的内容是 2班和1班名字相同的同学forEach是遍历集合,代替了for循环,代码更为简洁 collect(Collectors.toList()) 、collect(Collectors.toSet()) 、collect(Collectors.toMap()) 将Stream的数据归集到List、Map、Set等集合二、差集
输出结果:b c @Test public void test(){ List list01=Arrays.asList("a","b","c"); List list02=Arrays.asList("a","e","f"); //list01和list02的差集, 仅保留了 b,c List result=list01.stream().filter(word->!list02.contains(word)).collect(Collectors.toList()); result.stream().forEach(word->System.out.print(word+" ")); }
表达式 list01.stream().filter(word-> ! list02.contains(word)) ,要找的元素,它的特征是只存在list01中,但不存在list02中,! list02.contains(word) 就是说这个元素不在list02中三、去重
输出结果:a b c List list=Arrays.asList("a","b","c","a"); List distinct=list.stream().distinct().collect(Collectors.toList()); distinct.stream().forEach(word->System.out.print(word+" "));
删除了重复的字符"a" 四、list.stream()构造方法
可能有朋友对 list.stream() 有些疑惑,它是个Stream的构造方法,Stream的构造方法如下:用集合创建Stream List list=Arrays.asList( "a" ,"b" ,"c" );
//创建顺序流
Stream stream=list.stream();
//创建并行流
StreamparallelStream=list.parallelStream();用数组 Arrays.stream(array) 创建Streamint [] array={1 ,2 ,3 ,4 ,5 };
IntStream stream=Arrays.stream(array);用 Stream of(T... values) 创建StreamStream stream=Stream.of( 1 ,2 ,3 ,4 ,5 );
常用的是上面这三种,另外还有 iterate() ,generate() ,后者是生成随机数,两个构造方法均产生无限流(即元素的个数是无限的)。
如果要求数量有限,则需要用 limit 来限制,如: Stream stream=Stream.iterate(0,num->num+3).limit(10)
打印了 [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]