【新特性】Java8新特性stream的用法

前言

Java 8 API添加了一个新的抽象称为流Stream,可以以一种声明的方式处理数据。
Stream(流)是一个来自数据源的元素队列并支持聚合操作。Java8中可以通过串行流stream()和并行流parallelStream()生成流

stream 应用

list集合分组后按时间排序取最近的一条记录

集合按照id进行分组后,按照时间顺序取最近一条记录

List<Documnet> list = new ArrayList<>();
Map<String, Document> map = list.parallelStream().collect(Collectors.groupingBy(data -> data.getString("id"),
        Collectors.collectingAndThen(Collectors.reducing(
                (c1, c2) -> DateUtil.compare(c1.getDate("data_time"), c2.getDate("data_time")) > 0 ? c1 : c2), 
                Optional<Document>::get
        )));

对List元素通过某个值进行排序

List<User> list = new ArrayList<>();
// 正序
List<User> collect = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
//倒序
List<User> collect = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
//常用数据类型排序
List<Date> dateList = new ArrayList<>();
List<Date> collect =dateList.stream().sorted().collect(Collectors.toList());
List<Date> collect =dateList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

对List集合中元素进行字符串拼接

//简单的List<String> 可以通过String.join来实现字符串拼接
List<String> strs = new ArrayList<>();
String.join("", strs);
//对象列表,需要其中某个字段进行拼接时可用下面方法进行操作
List<User> list = new ArrayList<>();
list.stream().map(User::getName).collect(Collectors.joining(","));

List集合转换成map的几种情况

1、通过toMap()将list转换成map
java8中toMap方法
参数 mergeFunction 的作用是当出现 key 重复时,自定义对value 的处理策略

List<User> list = new ArrayList<>();
// list转换成map key为ID,value为name
Map<Long, String> map = list.stream().collect(Collectors.toMap(User::getId,User::getName));
// list转换成map key为ID,value为user对象
Map<Long, String> map = list.stream().collect(Collectors.toMap(User::getId, user->user));
Map<Long, String> map = list.stream().collect(Collectors.toMap(User::getId, Function.identity()));
// list转换成map key为ID,value为user对象,如果存在重复key时,取其中第一个数据k1
Map<Long, String> map = list.stream().collect(Collectors.toMap(User::getId, Function.identity(), (k1,k2) -> k1));

Function.identity()方法Function是一个接口,identity是接口下的一个方法,返回一个lambda函数表达式,即输出内容为输入内容

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }

2、 通过groupingBy()实现分组转换成map

List<User> list = new ArrayList<>();
//1、通过性别对用户进行分组
Map<String, List<User>> map = list.stream().collect(Collectors.groupingBy(User::getSex));
//2、先通过性别对用户进行分组,在对分组后的用户通过年龄进行分组
Map<String, Map<Integer, List<User>>> map = list.stream().collect(Collectors.groupingBy(User::getSex, Collectors.groupingBy(User::getAge)));
//3、先通过性别对用户进行分组,分组后仅展示用户年龄集合(可通过toList(),toSet()选择具体是list还是set集合)
	Map<String, List<Integer>> map3 = list.stream().collect(
                Collectors.groupingBy(User::getSex,
                        Collectors.mapping(User::getAge, Collectors.toList())
                ));
//4、先通过性别进行分组,分组后对年龄进行求和(可通过summingInt,averagingInt等方法进行求和求平均等计算)
        Map<String, Integer> map = list.stream().collect(
                Collectors.groupingBy(User::getSex,
                        Collectors.summingInt((User::getAge)
                        )));

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值