Java-Steam流的使用

先贴一个计算花费时间的小方法

        //开始计时
        Long startTime = System.currentTimeMillis();
        //计时结束
        Long endTime = System.currentTimeMillis();
        Long tempTime = (endTime - startTime);System.out.println(showTimeByTemp(tempTime));
        System.out.println(showTimeByTemp(tempTime));
    /**
     * @Description :根据时间戳输出如 18640 d 2 h 59 m 34 s 752 ms的时间长度,用于计算耗时
     * @param tempTime: 时间戳
     * @Return : java.lang.String
     */
    public static String showTimeByTemp(Long tempTime){
        return "花费时间:" +
                (((tempTime / 86400000) > 0) ? ((tempTime / 86400000) + " d ") : "") +
                ((((tempTime / 86400000) > 0) || ((tempTime % 86400000 / 3600000) > 0)) ? ((tempTime % 86400000 / 3600000) + " h ") : ("")) +
                ((((tempTime / 3600000) > 0) || ((tempTime % 3600000 / 60000) > 0)) ? ((tempTime % 3600000 / 60000) + " m ") : ("")) +
                ((((tempTime / 60000) > 0) || ((tempTime % 60000 / 1000) > 0)) ? ((tempTime % 60000 / 1000) + " s ") : ("")) +
                ((tempTime % 1000) + " ms ");
    }
实体类
@Data
public class TestEntity {
    private int id;
    private String name;
    private Date birthday;
    private Date createTime;
    private Date editTime;
}
Steam.map

对list中的对象进行一对一的映射,可用于抽取对象中的一个或多个属性

        List<TestEntity> collect = testEntityList.stream().map(testEntity -> {
            testEntity.setBirthday(new Date());
            testEntity.setCreateTime(new Date());
            return testEntity;
        }).distinct().collect(Collectors.toList());
Steam.distinct list.distinct()

去重,去除list中重合的元素。

Steam.limit list.limit(10000)

获取list中前10000个参数。

filter 筛选

条件为false的对象会从list中去除

        List<TestEntity> wlm = testEntityList
                .stream()
                .filter(testEntity -> testEntity.getName().equals("wlm"))
                .collect(Collectors.toList());
.sorted 排序

简单的写法,对类中的属性进行排序。

                .sorted(Comparator
                        .comparing(TestEntity::getId)
                        .reversed()//按照id倒序排序
                        .thenComparing((testEntity) -> testEntity.getName())//按照name正序排序
                        .thenComparing((testEntity) -> testEntity.getEditTime()))//按照EditTime正序排序
                .collect(Collectors.toList());

进行复杂一点的排序判断,不使用lambda

//        对list进行排序
        Collections.sort(testEntityList, new Comparator<TestEntity>() {
            @Override
            public int compare(TestEntity o1, TestEntity o2) {
                int a = o1.getId()*30 + o1.getName().length()*20;
                int b = o2.getId()*30 + o2.getName().length()*20;
                return  a-b;
            }
        });

进行复杂一点的排序判断,使用lambda

//        对list进行排序
        Collections.sort(testEntityList, (o1, o2) -> {
            int a = o1.getId()*30 + o1.getName().length()*20;
            int b = o2.getId()*30 + o2.getName().length()*20;
            return  a-b;
        });
.max和.min

得到最大值和最小值

        //相同的排序逻辑
        //stream流取最大值 .max()
        Optional<TestEntity> max = testEntityList.stream().max((t1, t2) -> {
            int a = t1.getId() * 10 + t1.getName().length() * 20;
            int b = t2.getId() * 10 + t2.getName().length() * 20;
            return a - b;
        });
        TestEntity testEntityMax = max.get();
        System.out.println(testEntityMax);
        //stream流取最小值 .mix()
        Optional<TestEntity> min = testEntityList.stream().min((t1, t2) -> {
            int a = t1.getId() * 10 + t1.getName().length() * 20;
            int b = t2.getId() * 10 + t2.getName().length() * 20;
            return a - b;
        });
        TestEntity testEntityMin = min.get();
        System.out.println(testEntityMin);
.collect聚合

聚合可以将stream流重新聚合为list也可以将list聚合成其他类型,如map,set,string等等,也可以使用聚合进行求和分组等操作。
聚合为List

        testEntityList
                .stream()
                .filter(testEntity -> testEntity.getId() > 0 )
                .collect(Collectors.toList());

聚合为map

        //只需要两个属性
        Map<Integer, String> collect2 = testEntityList
                .stream()
                .collect(Collectors
                        .toMap(TestEntity::getId, TestEntity::getName));

        //当需要计算对象的对应的各种数值时
        Map<TestEntity, Integer> collect3 = testEntityList
                .stream()
                .collect(
                        Collectors
                                .toMap(
                                        //key
                                        testEntity -> {
                                            return testEntity;
                                        }
                                        , 
                                        //value
                                        testEntity -> {
                                            int num = testEntity.getId() * 10 + testEntity.getName().length();
                                            return num;
                                        }
                                )
                );

当map中的key发生冲突时,需要重写方法进行冲突解决

        //当需要计算对象的对应的各种数值时
        Map<Integer, String> collect3 = testEntityList
                .stream()
                .collect(
                        Collectors
                                .toMap(
                                        //key
                                        testEntity -> {
                                            return testEntity.getId();
                                        }
                                        , 
                                        //value
                                        testEntity -> {
//                                            int num = testEntity.getId() * 10 + testEntity.getName().length();
//                                            return 10;
                                            return testEntity.getName();
                                        }
                                        ,
                                        //(非必填参数)当key发生冲突时,
                                        (s1, s2) ->  {
                                            return s1.concat(s2);
                                        }
                                )
                );
分组聚合

将list按照某个属性进行分组

        Map<Date, List<TestEntity>> listMap = testEntityList
                .stream()
                .collect(Collectors.groupingBy(TestEntity::getBirthday));

改变聚合后的对象类型

            Map<String, List<Long>> dbMap = threadOptionUsers.stream().collect(
                    Collectors.groupingBy(
                            t -> t.getThreadId().toString(),
                            Collectors.mapping(ThreadOptionUser::getThreadOptionId, Collectors.toList())
                    )
            );
聚合时将List<String>变为a,b,c的样式

注意,该方法只能对String类型的list使用

//输出为:前缀-a,b,c,d,e-后缀
        String streamJoining = testEntityList
                .stream()
                .map(entity -> entity.getName())
                //参数为:分隔符,前缀,后缀
                .collect(Collectors.joining(",", "前缀-", "-后缀"));
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容