Stream

82 阅读3分钟

引言

Stream是java8提供的API,是对集合容器的增强,提供非常高效的聚合操作,提高编程的效率和可读性。Stream并不保存数据,高效的对数据进行遍历并执行某些操作,做出相应的数据转换。

Stream操作步骤

  1. 创建Stream
  2. 一个中间链,对数据源进行操作

映射map

接收Lambda,将元素转换成其他形式或提取信息,并返回一个流,

接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。

Stream<Integer> streams = Stream.of(1, 2, 3, 4, 5);
streams.map(d ->  d + 2).forEach(System.out::println);

筛选filter

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

List<Integer> list = Arrays.asList(6, 7, 3, 8, 1, 2, 9);    
Stream<Integer> stream = list.stream();     
stream.filter(x -> x > 7).forEach(System.out::println);

聚合(max/min/count)

maxmincount这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计。Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。

public class StreamTest {
    public static void main(String[] args) {
        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());
    }
}
​
​

归约(reduce)

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

// 求乘积
Optional<Integer> product = list.stream().reduce((x, y) -> x * y);

排序(sorted)

List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());

终止操作

执行中间操作结果,并产生结果

收集(collect)

,流不存储数据,将流中的数据完成处理后,将流收集起来,变成一个值也可以是一个新的集合

归集(toList/toSet/toMap)

Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000)
                .collect(Collectors.toMap(Person::getName, p -> p));

统计(count/averaging)

Long count = personList.stream().collect(Collectors.counting());

分组(partitioningBy/groupingBy)

  • partitioningBy分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
  • groupingBy分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
作者:老刘
链接:https://zhuanlan.zhihu.com/p/299064490
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
​
public class StreamTest {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, "male", "New York"));
        personList.add(new Person("Jack", 7000, "male", "Washington"));
        personList.add(new Person("Lily", 7800, "female", "Washington"));
        personList.add(new Person("Anni", 8200, "female", "New York"));
        personList.add(new Person("Owen", 9500, "male", "New York"));
        personList.add(new Person("Alisa", 7900, "female", "New York"));
​
        // 将员工按薪资是否高于8000分组
        Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
        // 将员工按性别分组
        Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
        // 将员工先按性别分组,再按地区分组
        Map<String, Map<String, List<Person>>> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
        System.out.println("员工按薪资是否大于8000分组情况:" + part);
        System.out.println("员工按性别分组情况:" + group);
        System.out.println("员工按性别、地区:" + group2);
    }
}

作者:老刘 链接:zhuanlan.zhihu.com/p/299064490 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。