1 合并多个流
//合并多个流 private void merge() { List<String> list = new ArrayList<String>(); list.add("I am a boy"); list.add("I love the girl"); list.add("But the girl loves another girl"); List<String> result = list.stream() //得到流 .map(line->line.split(" ")) //将每个元素转成String[] .flatMap(Arrays::stream) //将每个String[] 转成流 ,并合并为一个大流 .distinct() //对元素去重 .collect(Collectors.toList()); //终止流得到集合 result.forEach(System.out::println); //打印 }
2 是否匹配任一元素
//是否匹配任一元素 private void anyMatch() { List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19)); boolean isHas = persons.stream().anyMatch(e -> e.getAge() == 18); System.out.println("isHas : "+isHas); }
3 是否所有元素都匹配
//是否所有元素都匹配 private void allMatch() { List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19)); boolean bool = persons.stream().allMatch(e -> e.getAge() == 18); System.out.println("isHas : "+bool); }
4 是否所有元素都不匹配
//是否所有元素都不匹配 private void noneMatch() { List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19)); boolean bool = persons.stream().noneMatch(e -> e.getAge() == 20); System.out.println("isHas : "+bool); }
5 新增容器optional (存储一个对象或者不存,可以避免空指针异常)
private void findFirst() { List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19)); Optional<Person> optional = persons.stream().findFirst(); System.out.println(optional.get().getName()); }
6 归并 reduce
//归并 private void testReduce() { List<Person> persons = Arrays.asList(new Person("zhangsan", 18),new Person("lisi", 19)); //reduce 不设置初始值 Optional<Integer> optional = persons.stream().map(e -> e.getAge()).reduce((a,b) -> a + b); System.out.println(optional.get()); //reduce 设置初始值 Integer ageTotal = persons.stream().map(e -> e.getAge()).reduce(0,(a,b) -> a + b); System.out.println(ageTotal); }