0
点赞
收藏
分享

微信扫一扫

Java8 Stream的使用

南柯Taylor 2021-09-19 阅读 125
JAVA基础

概述

Stream是jdk1.8的新特性,可以结合lambada表达式结合使用,可以提高开发效率和性能。

Stream流的作用

1、用于对集合迭代的增强处理
2、可以对集合数组进行更高效的聚合操作,比如分组,过滤,排序,元素的追加
3、解决传统开发中,jdk对集合或者数组API不足的问题,在早期的api开发中,对集合map的操作其实是比较单一的。在jdk1.8之后就参考了很多语言的一些对数组集合操作的api

Stream完成排序

public static void main(String[] args) {
        List<Category> categoryList = new ArrayList<>();
        categoryList.add(new Category(1L,"Java","java",0L,1));
        categoryList.add(new Category(2L,"JavaScript","JavaScript",0L,5));
        categoryList.add(new Category(3L,"PHP","PHP",0L,2));
        categoryList.add(new Category(4L,"Go","Go",0L,8));
        categoryList.add(new Category(5L,"Ruby","Ruby",0L,3));
        // 将集合装入stream管道中
        // 对管道进行排序
        // 将排好序的stream流装入集合中,则集合排好序
        List<Category> collect = categoryList.stream().sorted(new Comparator<Category>() {
            @Override
            public int compare(Category o1, Category o2) {
                return o1.getSort() - o2.getSort();
            }
        }).collect(Collectors.toList());

        collect.forEach(System.out::println);
    }

Stream过滤

过滤就是把过滤条件满足的元素找到

List<Category> collect1 = categoryList.stream().
                       filter(cass ->  cass.getId().equals(1L) ).collect(Collectors.toList());

 collect1.forEach(System.out::println);

map改变集合中每个元素的信息

// map改变集合中元素信息
        List<Category> collect2 = categoryList.stream().map(cass -> {
            cass.setTitle(cass.getTitle() + "_sssss");
            return cass;
        }).collect(Collectors.toList());

        collect2.forEach(System.out::println);

distinct 集合去重

distinct 去重,,如果集合是对象,就要对象返回相同的hashcode和equals 才会去重

// distinct 去重,,如果集合是对象,就要对象返回相同的hashcode和equals 才会去重
        List<Category> collect3 = categoryList.stream().distinct().collect(Collectors.toList());
        collect3.forEach(System.out::println);

reduce 对集合元素求和

// reduce 对集合元素求和,求价格总额
        Integer reduces = categoryList.stream().map(ress -> {
            return ress.getSort();
        }).reduce(0, (c1, c2) -> c1 + c2);
        System.out.println(reduces);

举报

相关推荐

0 条评论