Java8新特性之Stream流(含具体案例)

您所在的位置:网站首页 stream的词性 Java8新特性之Stream流(含具体案例)

Java8新特性之Stream流(含具体案例)

#Java8新特性之Stream流(含具体案例)| 来源: 网络整理| 查看: 265

一、概述

Stream 流是 Java 8 新提供给开发者的一组操作集合的 API,将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选、排序、聚合等。元素流在管道中经过中间操作(intermediate operation)的处理,最后由终端操作 (terminal operation) 得到前面处理的结果。Stream 流可以极大的提高开发效率,也可以使用它写出更加简洁明了的代码。我自从接触过 Stream 流之后,可以说对它爱不释手。

二、Stream的创建

Stream可以通过集合数组创建。

1、通过 java.util.Collection.stream() 方法用集合创建流

List list = Arrays.asList("a", "b", "c"); // 创建一个顺序流 Stream stream = list.stream(); // 创建一个并行流 Stream parallelStream = list.parallelStream();

2、使用java.util.Arrays.stream(T[] array)方法用数组创建流

int[] array={1,3,5,7,9}; IntStream stream = Arrays.stream(array);

3、使用Stream的静态方法:of()、iterate()、generate()

Stream stream = Stream.of(1, 2, 3, 4, 5, 6); Stream stream2 = Stream.iterate(0, (x) -> x + 3).limit(4); stream2.forEach(System.out::println); Stream stream3 = Stream.generate(Math::random).limit(3); stream3.forEach(System.out::println);

输出结果:

0 3 6 9 0.6796156909271994 0.1914314208854283 0.8116932592396652

stream和parallelStream的简单区分:

stream是顺序流,由主线程按顺序对流执行操作,而parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求。如果流中的数据量足够大,并行流可以加快处速度。除了直接创建并行流,还可以通过parallel()把顺序流转换成并行流:

Optional findFirst = list.stream().parallel().filter(x->x>6).findFirst();三、Stream的使用(具体案例)  案例中用到的员工类:/** * @description: 员工 * @author: admin */ @Data public class Person { /*** 姓名*/ private String name; /*** 薪资*/ private Integer salary; /*** 年龄*/ private Integer age; /*** 性别*/ private String sex; /*** 地区*/ private String area; public Person(String name, Integer salary, Integer age, String sex, String area) { this.name = name; this.salary = salary; this.age = age; this.sex = sex; this.area = area; } }1.遍历/匹配(foreach/find/match)

Stream也是支持类似集合的遍历和匹配元素的,只是Stream中的元素是以Optional类型存在的。Stream的遍历、匹配非常的简单。

public static void main(String[] args) { List list = Arrays.asList(7, 6, 9, 3, 8, 2, 1); // 遍历输出符合条件的元素 List collect = list.stream().filter(x -> x > 6).collect(Collectors.toList()); // 匹配第一个 Optional findFirst = list.stream().filter(x -> x > 6).findFirst(); // 匹配任意(适用于并行流) Optional findAny = list.parallelStream().filter(x -> x > 6).findAny(); // 是否包含符合特定条件的元素 boolean anyMatch = list.stream().anyMatch(x -> x > 6); System.out.println("大于6的值:" + collect); System.out.println("匹配第一个值:" + findFirst.get()); System.out.println("匹配任意一个值:" + findAny.get()); System.out.println("是否存在大于6的值:" + anyMatch); }

结果:

2.筛选(filter) 

 筛选,是按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中的操作。

public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "四川")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); // 筛选出工作高于3000的员工 List list = personList.stream().filter(p -> p.getSalary() > 3000).map(Person::getName).collect(Collectors.toList()); System.out.println("薪资高于3000元的员工:" + list); }

结果:

3.聚合(max/min/count) 

max、min、count这些大家都不陌生,在mysql中我们常用它们进行数据运算和统计。Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。

public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "四川")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); // 获取工资最高的员工 Optional max = personList.stream().max(Comparator.comparingInt(Person::getSalary)); System.out.println("员工工资最大值:" + max.get().getSalary()); // 计算工资大于2000的有多少人 long count = personList.stream().filter(p -> p.getSalary() > 2000).count(); System.out.println("工资大于2000元的人数:" + count); // 计算所有员工工资总和 int sum = personList.stream().mapToInt(Person::getSalary).sum(); System.out.println("所有员工工资总和:" + sum); }

结果:

4.映射(map/flatMap) 

映射,可以将一个流的元素按照一定的映射规则映射到另一个流中。分为map和flatMap:

map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。 public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "四川")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); // 将员工工作全部增加10000元 // 1、方式一:不改变原来员工集合 List 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()); // 2、方式二:改变原来员工集合的方式 List 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 list = Arrays.asList("Hello", "World"); Stream map = list.stream().map(s -> s.split("")).flatMap(Arrays::stream); map.forEach(System.out::print); System.out.println(); // 给定两个数字列表 获取所有的数对 List numbers1 = Arrays.asList(1, 2, 3); List numbers2 = Arrays.asList(3, 4); // flatMap升维度 List pairs = numbers1.stream().flatMap(x -> numbers2.stream().map(y -> new int[] { x, y })) .collect(Collectors.toList()); for (int[] pair : pairs) { System.out.print(Arrays.toString(pair)); } }

结果:

5.归约(reduce)

归约,也称缩减,顾名思义,是把一个流缩减成一个值,能实现对集合求和、求乘积和求最值操作。

public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "四川")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); // 求所有员工的工资之和、最高工资 // 求工资之和方法1: Optional sumSalary = personList.stream().map(Person::getSalary).reduce(Integer::sum); // 求工资之和方法2: Integer sumSalary2 = personList.stream().reduce(0, (sum, p) -> sum += p.getSalary(), Integer::sum); // 求最高工资方法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(), (max1, max2) -> max1 > max2 ? max1 : max2); // 求最高工资方法3: Integer maxSalary3 = personList.stream().map(Person::getSalary).reduce(Integer::max).get(); System.out.println("工资之和,方法1:" + sumSalary); System.out.println("工资之和,方法2:" + sumSalary2); System.out.println("最高工资,方法1:" + maxSalary); System.out.println("最高工资,方法2:" + maxSalary2); System.out.println("最高工资,方法3:" + maxSalary3); }

结果:

6.收集(collect) 

collect,收集,可以说是内容最繁多、功能最丰富的部分了。从字面上去理解,就是把一个流收集起来,最终可以是收集成一个值也可以收集成一个新的集合。

collect主要依赖java.util.stream.Collectors类内置的静态方法。

6.1归集(toList/toSet/toMap)

因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里。toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。

下面用一个案例演示toList、toSet和toMap:

public static void main(String[] args) { List list = Arrays.asList(1, 3, 4, 8, 6, 2, 20, 13); List list1 = list.stream().filter(a -> a % 2 == 0).collect(Collectors.toList()); Set list2 = list.stream().filter(a -> a % 2 == 0).collect(Collectors.toSet()); System.out.println("被2整除的list集合" + list1); System.out.println("被2整除的set集合" + list2); List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "四川")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); // 工资大于3000元的员工 Map map = personList.stream().filter(person -> person.getSalary() > 3000).collect(Collectors.toMap(Person::getName, person -> person.getSalary())); System.out.println("工资大于3000元的员工:" + map); }

结果:

6.2统计(count/averaging) 

Collectors提供了一系列用于数据统计的静态方法:

计数:count 平均值:averagingInt、averagingLong、averagingDouble 最值:maxBy、minBy 求和:summingInt、summingLong、summingDouble 统计以上所有:summarizingInt、summarizingLong、summarizingDouble

public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "四川")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); // 统计员工人数、平均工资、工资总额、最高工资 // 员工总人数 long count = personList.stream().count(); // 平均工资 Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary)); // 最高工资 Optional max = personList.stream().map(Person::getSalary).max(Integer::compare); // 工资之和 int sum = personList.stream().mapToInt(Person::getSalary).sum(); // 一次性统计所有信息 DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary)); System.out.println("员工总人数:" + count); System.out.println("员工平均工资:" + average); System.out.println("员工工资总和:" + sum); System.out.println("员工工资所有统计:" + collect); }

结果:

6.3分组(partitioningBy/groupingBy)分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。 public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "合肥")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); // 按薪资高于3000分组 Map salaryGroup = personList.stream().collect(Collectors.partitioningBy(p -> p.getSalary() > 3000)); List group1 = salaryGroup.get(true); List group2 = salaryGroup.get(false); for (Person person : group1) { System.out.println("薪资高于3000元组:" + person); } for (Person person : group2) { System.out.println("薪资低于3000元组:" + person); } // 按性别分组 Map sexGroup = personList.stream().collect(Collectors.groupingBy(Person::getSex)); List group3 = sexGroup.get("男"); List group4 = sexGroup.get("女"); for (Person person : group3) { System.out.println("男子组:" + person); } for (Person person : group4) { System.out.println("女子组:" + person); } // 将员工先按性别分组,再按地区分组 Map group = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea))); Map manGroup = group.get("男"); Map womenGroup = group.get("女"); List group5 = manGroup.get("合肥"); List group6 = womenGroup.get("上海"); System.out.println("地区在合肥的男子组:" + group5); System.out.println("地区在上海的女子组:" + group6); }

结果:

6.4接合(joining) 

joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。

public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 1000, 20, "男", "北京")); personList.add(new Person("李四", 2000, 21, "男", "南京")); personList.add(new Person("王五", 3000, 20, "女", "合肥")); personList.add(new Person("赵六", 4000, 22, "男", "合肥")); personList.add(new Person("孙七", 5000, 25, "女", "上海")); String persons = personList.stream().map(p -> p.getName() + "-" + p.getSex() + "-" + p.getSalary()).collect(Collectors.joining(",")); System.out.println("所有员工信息:" + persons); }

结果:

6.5归约(reducing) 

Collectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持。

public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 6000, 20, "男", "北京")); personList.add(new Person("李四", 6500, 21, "男", "南京")); personList.add(new Person("王五", 7300, 20, "女", "合肥")); personList.add(new Person("赵六", 8000, 22, "男", "合肥")); personList.add(new Person("孙七", 9860, 25, "女", "上海")); // 每个员工减去起征点后的薪资之和(这里个税的算法并不正确,但没想到更好的例子) Integer sum = personList.stream().map(Person::getSalary).reduce(0, (i, j) -> (i + j - 5000)); System.out.println("员工扣税薪资总和:" + sum); // stream的reduce Optional sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum); System.out.println("员工薪资总和:" + sum2.get()); }

结果:

7.排序(sorted)

sorted,中间操作。有两种排序:

sorted():自然排序,流中元素需实现Comparable接口sorted(Comparator com):Comparator排序器自定义排序 public static void main(String[] args) { List personList = new ArrayList(); personList.add(new Person("张三", 16000, 20, "男", "北京")); personList.add(new Person("李四", 8500, 21, "男", "南京")); personList.add(new Person("王五", 7300, 20, "女", "合肥")); personList.add(new Person("赵六", 8000, 22, "男", "合肥")); personList.add(new Person("孙七", 15860, 25, "女", "上海")); // 按工资升序排序(自然排序) List newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList()); // 按工资倒序排序 List newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList()); // 先按工资再按年龄升序排序 List newList3 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList()); // 先按工资再按年龄自定义排序(降序) List newList4 = personList.stream().sorted((p1, p2) -> { if (p1.getSalary().equals(p2.getSalary())) { return p2.getAge() - p1.getAge(); } else { return p2.getSalary() - p1.getSalary(); } }).map(Person::getName).collect(Collectors.toList()); System.out.println("按工资升序排序:" + newList); System.out.println("按工资降序排序:" + newList2); System.out.println("先按工资再按年龄升序排序:" + newList3); System.out.println("先按工资再按年龄自定义降序排序:" + newList4); }

结果:

8.提取/组合

流也可以进行合并、去重、限制、跳过等操作。

public static void main(String[] args) { String[] arr1 = {"a", "b", "c", "d"}; String[] arr2 = {"d", "e", "f", "g"}; Stream stream1 = Stream.of(arr1); Stream stream2 = Stream.of(arr2); // concat:合并两个流 distinct:去重 List newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()); // limit:限制从流中获得前n个数据 List collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList()); // skip:跳过前n个数据 List collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList()); System.out.println("流合并:" + newList); System.out.println("limit:" + collect); System.out.println("skip:" + collect2); }

结果:



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3