> 文档中心 > Stream流的学习笔记

Stream流的学习笔记

  • stream的学习笔记
  • 知识来源于: Java8 Stream:2万字20个实例,玩转集合的筛选、归约、分组、聚合
  • 详细的图解请查看上文,该部分代码是方便自己查阅使用
package com.jd.code.day3;import java.util.*;import java.util.stream.Collectors;import java.util.stream.IntStream;import java.util.stream.Stream;/ * stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。 * stream不会改变数据源,通常情况下会产生一个新的集合或一个值。 * stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。 */public class StreamTest {    public static List<Person> personList = new ArrayList<Person>();    public static void init() { personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York"));    }    public static void main(String[] args) { init();    }    /     * 提取/组合     *    流也可以进行合并、去重、限制、跳过等操作。     */    public static void test13(){ String[] arr1 = { "a", "b", "c", "d" }; String[] arr2 = { "d", "e", "f", "g" }; Stream<String> stream1 = Stream.of(arr1); Stream<String> stream2 = Stream.of(arr2); // concat:合并两个流 distinct:去重 List<String> collect = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()); System.out.println("collect = " + collect); // limit:限制从流中获得前n个数据 List<Integer> collect1 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList()); System.out.println("collect1 = " + collect1); // skip:跳过前n个数据 List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(4).collect(Collectors.toList()); System.out.println("collect2 = " + collect2);    }    /     * 排序(sorted)     * sorted,中间操作。有两种排序:     * sorted():自然排序,流中元素需实现Comparable接口     * sorted(Comparator com):Comparator排序器自定义排序     */    public static void test12() { // 案例:将员工工资由高到低(工资一样则按年龄由大到小)排序 // 按照工资进行排序,自然排序 List<String> collect = personList.stream()  .sorted(Comparator.comparing(Person::getSalary))  .map(Person::getName)  .collect(Collectors.toList()); System.out.println("collect = " + collect); // 按照工资进行倒序 List<Integer> collect1 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())  .map(Person::getSalary)  .collect(Collectors.toList()); System.out.println("collect1 = " + collect1); // 先按照工资再按照年龄进行升序排序 List<String> collect2 = personList.stream()  .sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge))  .map(Person::getName)  .collect(Collectors.toList()); System.out.println("collect2 = " + collect2); // 先按工资再按照年龄倒序 List<String> collect3 = personList.stream().sorted((p1, p2) -> {     if (p1.getSalary() == p2.getSalary()) {  return p2.getAge() - p1.getAge();     } else {  return p2.getSalary() - p1.getSalary();     } }).map(Person::getName).collect(Collectors.toList()); System.out.println("collect3 = " + collect3);    }    /     * 归约(reducing)     * Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。     */    public static void test11() { // 每个员工减去起征点后的薪资之和(这个例子并不严谨,但一时没想到好的例子) Integer collect = personList.stream()  .collect(Collectors.reducing(0,   Person::getSalary,   (i, j) -> (i + j - 5000))); System.out.println("collect = " + collect); // stream的reduce Optional<Integer> sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum); System.out.println("员工薪资总和:" + sum2.get());    }    /     * 接合(joining)     * joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。     */    public static void test10() { String joinStr = personList.stream()  .map(person -> person.getName())  .collect(Collectors.joining(", ")); System.out.println("joinStr = " + joinStr); List<String> list = Arrays.asList("A", "B", "C"); String str = list.stream().collect(Collectors.joining("-")); System.out.println("str = " + str);    }    /     * 分组(partitioningBy/groupingBy)     * 分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。     * 分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。     */    public static void test09() { // 案例:将员工按薪资是否高于8000分为两部分;将员工按性别和地区分组 Map<Boolean, List<Person>> part =  personList.stream().collect(Collectors.partitioningBy(person -> person.getSalary() > 8000)); System.out.println("part = " + part); // 将员工按照性别进行分组 Map<String, List<Person>> sexMap = personList.stream().collect(Collectors.groupingBy(Person::getSex)); System.out.println("sexPart = " + sexMap); // 将员工先按照性别进行分组,再按照地区进行分组 Map<String, Map<String, List<Person>>> sexAndAreaGroup =  personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea))); System.out.println("sexAndAreaGroup = " + sexAndAreaGroup);    }    /     * 统计(count/averaging)     * Collectors提供了一系列用于数据统计的静态方法:     * 计数:count     * 平均值:averagingInt、averagingLong、averagingDouble     * 最值:maxBy、minBy     * 求和:summingInt、summingLong、summingDouble     * 统计以上所有:summarizingInt、summarizingLong、summarizingDouble     */    public static void test08() { // 案例:统计员工人数、平均工资、工资总额、最高工资。 long count = personList.stream().count(); System.out.println("count = " + count); // 平均工资 Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary)); System.out.println("average = " + average); // 工资总和 Double sum = personList.stream().collect(Collectors.summingDouble(Person::getSalary)); System.out.println("sum = " + sum); // 最高工资 Optional<Person> maxSalary = personList.stream().max(Comparator.comparing(Person::getSalary)); System.out.println("maxSalary.get() = " + maxSalary.get().getSalary());    }    /     * 收集(collect)     * collect,收集,可以说是内容最繁多、功能最丰富的部分了。从字面上去理解,就是把一个流收集起来,     * 最终可以是收集成一个值也可以收集成一个新的集合。     * collect主要依赖java.util.stream.Collectors类内置的静态方法。     */    /     * 归集(toList/toSet/toMap)     * 因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。     * toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。     */    public static void test07() { List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20); // 取出所有的奇数 List<Integer> list1 = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); System.out.println("list1 = " + list1); Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); System.out.println("set = " + set); // 找出薪资大于8000的人员 Map<String, Person> map = personList.stream().filter(p -> p.getSalary() > 8000)  .collect(Collectors.toMap(Person::getName, p -> p)); System.out.println("map = " + map);    }    /     * 归约(reduce)     * 归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。     */    public static void test06() { // 案例一:求Integer集合的元素之和、乘积和最大值。 List<Integer> list = Arrays.asList(1, 3, 2, 8, 11, 4); // 方法1 Optional<Integer> sum = list.stream().reduce((x, y) -> x + y); // 方法2 Optional<Integer> sum2 = list.stream().reduce(Integer::sum); // 方法3 Integer sum3 = list.stream().reduce(0, Integer::sum); System.out.println("列表求和 = " + sum.get()); System.out.println("sum2.get() = " + sum2.get()); System.out.println("sum3 = " + sum3); // 列表的乘积 Optional<Integer> product = list.stream().reduce((x, y) -> x * y); System.out.println("product.get() = " + product.get()); // 返回最大值 Optional<Integer> max = list.stream().reduce((x, y) -> x > y ? x : y); System.out.println("max.get() = " + max.get()); // 直接使用max函数求最大值 Optional<Integer> max1 = list.stream().max(Integer::compareTo); System.out.println("max1.get() = " + max1.get()); // 使用reduce求解最大值 Integer max2 = list.stream().reduce(1, Integer::max); System.out.println("max2 = " + max2); // 案例二:求所有员工的工资之和、最高工资。 Optional<Integer> salarySum = personList.stream().map(Person::getSalary) // 取出所有的工资  .reduce(Integer::sum); System.out.println("salarySum.get() = " + salarySum.get()); // 方法2: // Integer salarySum2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), (sum1, sum2) -> sum1 + sum2); // System.out.println("salarySum2 = " + salarySum2); // 方法3: // 求工资之和方式3: // Integer sumSalary3 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum); // 求出工资的最大值 Optional<Integer> max3 = personList.stream().map(Person::getSalary).max(Integer::compareTo); System.out.println("max3.get() = " + max3.get()); // 使用reduce求解最大值 // 求最高工资方式1: // Integer maxSalary = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), //  Integer::max); // // 求最高工资方式2: // Integer maxSalary2 = personList.stream().reduce(0, (max, p) -> max > p.getSalary() ? max : p.getSalary(), //  (max11, max22) -> max11 > max22 ? max11 : max22); // // System.out.println("最高工资:" + maxSalary + "," + maxSalary2);    }    /     * 映射(map/flatMap)     * 映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap:     * map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。     * flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。     */    public static void test05() { // 案例一:英文字符串数组的元素全部改为大写。 String[] strArr = {"abcd", "bcdd", "defde", "fTr"}; List<String> stringList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList()); System.out.println("stringList = " + stringList); // 整数数组每个元素+3。 List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11); List<Integer> integerList = intList.stream().map(x -> x + 3).collect(Collectors.toList()); System.out.println("integerList = " + integerList); // 案例二:将员工的薪资全部增加1000 List<Integer> newPersonList = personList.stream().map(person -> person.getSalary() + 1000)  .collect(Collectors.toList()); System.out.println("newPersonList = " + newPersonList); // 不改变原来员工集合的方式 List<Person> personListNew = personList.stream().map(person -> {     Person personNew = new Person(person.getName(), 0, 0, null, null);     personNew.setSalary(person.getSalary() + 10000);     return personNew; }).collect(Collectors.toList()); System.out.println("一次改动前:" + personList.get(0).getName() + "-->" + personList.get(0).getSalary()); System.out.println("一次改动后:" + personListNew.get(0).getName() + "-->" + personListNew.get(0).getSalary()); // 改变原来员工集合的方式 List<Person> personListNew2 = personList.stream().map(person -> {     person.setSalary(person.getSalary() + 10000);     return person; }).collect(Collectors.toList()); System.out.println("二次改动前:" + personList.get(0).getName() + "-->" + personListNew.get(0).getSalary()); System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary()); // 案例三:将两个字符数组合并成一个新的字符数组 List<String> list4 = Arrays.asList("m,k,l,a", "1,3,5,7"); List<String> listNew = list4.stream().flatMap(s -> {     String[] split = s.split(",");     Stream<String> s2 = Arrays.stream(split);     return s2; }).collect(Collectors.toList()); System.out.println("处理前的集合: " + list4); System.out.println("处理后的集合: " + listNew);    }    /     * 3.聚合(max/min/count)     * max、min、count这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计。     * Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。     */    public static void test04() { // 案例一:获取String集合中最长的元素。 List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd"); Optional<String> max = list.stream().max(Comparator.comparing(String::length)); System.out.println("max.get() = " + max.get()); // 案例二:获取Integer集合中的最大值。 List<Integer> list1 = Arrays.asList(7, 6, 9, 4, 11, 6); // 自然排序(大到小) Optional<Integer> max1 = list1.stream().max(Integer::compareTo); // 自定义排序(大到小) Optional<Integer> max2 = list1.stream().max(new Comparator<Integer>() {     @Override     public int compare(Integer o1, Integer o2) {  return o1.compareTo(o2);     } }); // 自然排序。自定义排序的最大值 System.out.println("max1.get() = " + max1.get()); System.out.println("max2.get() = " + max2.get()); // 案例三:获取员工工资最高的人。 // 方法1: // Optional person = personList.stream().max(new Comparator() { //     @Override //     public int compare(Person o1, Person o2) { //  return o1.getSalary() - o2.getSalary(); //     } // }); // 方法2 Optional<Person> person = personList.stream().max(Comparator.comparing(Person::getSalary)); System.out.println("工资的最大值 = " + person.get().getSalary()); // 案例四:计算Integer集合中大于6的元素的个数。 List<Integer> list2 = Arrays.asList(7, 6, 4, 8, 2, 11, 9); long count = list2.stream().filter(x -> x > 6).count(); System.out.println("count = " + count);    }    /     * 2.筛选(filter)     * 筛选,是按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作。     */    public static void test03() { List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1); // 筛选出Integer集合中大于7的元素,并打印出来 list.stream().filter(x -> x > 7).forEach(System.out::println); // 案例二: 筛选员工中工资高于8000的人,并形成新的集合。 形成新集合依赖collect(收集) List<String> newList = personList.stream()  .filter(person -> person.getSalary() > 8000) // 过滤出工资大于8000的  .map(person -> person.getName()) // 取出所有person的name属性  .collect(Collectors.toList()); // 将新的流转为list集合 System.out.println("工资大于8000的员工姓名: " + newList);    }    /     * 1.遍历/匹配(foreach/find/match)     * Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。Stream的遍历、匹配非常简单。     */    public static void test02() { List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1); // 输出符合条件的元素 // 1.输出所有大于6的元素 list.stream().filter(x -> x > 6).forEach(System.out::println); // 2.获取第一个大于6的元素 Optional<Integer> first = list.stream().filter(x -> x > 6).findFirst(); System.out.println("first.get() = " + first.get()); // 3.获取任意一个大于6的元素 Optional<Integer> any = list.stream().filter(x -> x > 6).findAny(); System.out.println("any.get() = " + any.get()); // 4.判断list中是否存在大于6的元素 boolean isMatch = list.stream().anyMatch(x -> x > 6); System.out.println("isMatch = " + isMatch);    }    // 集合创建Stream    // 使用数组创建流    public static void test01() { List<String> list = Arrays.asList("a", "b", "c"); // 创建一个顺序流 Stream<String> stream = list.stream(); // 创建一个并行流 Stream<String> parallelStream = list.parallelStream(); // 数组创建 int[] arr = {1, 2, 3, 4, 5}; IntStream stream1 = Arrays.stream(arr); // 使用Stream的静态方法:of,iterate,generate Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6); Stream<Integer> stream3 = Stream.iterate(0, x -> x + 3).limit(4); stream3.forEach(System.out::println); // Stream<Double> stream4 = Stream.generate(Math::random).limit(3); stream4.forEach(System.out::println);    }}