栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 8 stream的记录

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 8 stream的记录

Java 8 stream的记录
  • Java 8 stream
    • 1、什么是流
    • 2、如何生成流
      • 1、通过集合生成,应用中最常用的一种
      • 2、通过数组生成
      • 3、通过值生成
      • 4、通过文件生成
      • 5、通过函数生成
          • 1.iterator
          • 2.generator
    • 3、流的操作类型
    • 4、常规操作案例
        • collect 返回集合
        • reduce的介绍及用法
    • Steam之两个list间交集、并集、差集
    • list和tree相互转换
        • stream流式写法把list换为Tree
      • People.java
      • Zone.java

Java 8 stream

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

1、什么是流

流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,它不是数据结构并不保存数据,它的主要目的在于计算。
如果对以上函数接口不太理解的话,可参考另外一篇文章:Java 8 函数式接口
链接: Java 8 函数式接口

2、如何生成流

生成流的方式主要有五种

1、通过集合生成,应用中最常用的一种
List integerList = Arrays.asList(1, 2, 3, 4, 5, 6);
Stream stream = integerList.stream();
2、通过数组生成
int[] intArr = {1, 2, 3, 4, 5, 6};
IntStream stream = Arrays.stream(intArr);

通过Arrays.stream方法生成流,并且该方法生成的流是数值流【即IntStream】而不是 Stream。补充一点使用数值流可以避免计算过程中拆箱装箱,提高性能。

Stream API提供了mapToInt、mapToDouble、mapToLong三种方式将对象流【即Stream 】转换成对应的数值流,同时提供了boxed方法将数值流转换为对象流.

3、通过值生成
Stream stream = Stream.of(1, 2, 3, 4, 5, 6);

通过Stream的of方法生成流,通过Stream的empty方法可以生成一个空流.

4、通过文件生成
Stream lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset());

通过Files.line方法得到一个流,并且得到的每个流是给定文件中的一行

5、通过函数生成 1.iterator
Stream stream = Stream.iterate(0, n -> n + 2).limit(5);

iterate方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为iterator生成的流为无限流,通过limit方法对流进行了截断,只生成5个偶数。

2.generator
Stream stream = Stream.generate(Math::random).limit(5);

generate方法接受一个参数,方法参数类型为Supplier ,由它为流提供值。generate生成的流也是无限流,因此通过limit对流进行了截断。

3、流的操作类型

操作分类

stream操作分类
中间操作无状态
(stateless)
unordered() fillter() map() mapToInt() peek() mapToDouble() flatMap() ...
有状态
(staeful)
distinct() sorted() limit() skip() ...
结束操作非短路操作
(non-short-circuit operation)
forEach() forEachOrderd() toArray() reduce() collect() max() min() count() ...
短路操作
(short circuit operation)
anyMatch() allMatch() noneMatch() findFirst() findAny()
4、常规操作案例
public class StreamDemo {
    static List list = null;

    //初始化数据
    static  {
        list = Arrays.asList(
                new People("1", "Tom", 88, 90),
                new People("2", "Jerry", 77, 89),
                new People("3", "Lily", 98, 79),
                new People("4", "Lucy", 70, 80),
                new People("5", "赵二", 88, 90),
                new People("6", "HanMeiMei", 87, 79));
    }

    public void streamtest() {
        // filter 过滤器返回还是一个stream流对象
        //查询math成绩大于80的学生并遍历输出
        list.stream().filter(e -> e.getMath() > 80).forEach(System.out::println);//.forEach(e->System.out.println(e))
        //统计数量count
        System.out.println(list.stream().count());
        //如统计总分大于160的人数
        System.out.println(list.stream().filter(e -> e.getEnglish() + e.getMath() > 160).count());
        //limit  取前n个值
        list.stream().limit(3).forEach(System.out::println);
        //skip 跳过前n个
        list.stream().skip(2).forEach(System.out::println);
        //distinct 去除重复数据
        list.stream().distinct().forEach(System.out::println);
        //map 映射元素可以对元素进行操作   例如对每个人年龄加1
        list.stream().map(e -> {
            e.setAge(e.getAge() + 1);
            return e;
        }).forEach(System.out::println);
        //sorted 排序
        //升序
        list.stream().sorted((a, b) -> {
            return a.getEnglish().compareTo(b.getEnglish());
        });
        List sortenList = list.stream().sorted(Comparator.comparing(People::getAge)).collect(Collectors.toList());
        //降序
        list.stream().sorted((a, b) -> {
            return b.getEnglish().compareTo(a.getEnglish());
        });
        //自定义排序:先按姓名升序,姓名相同则按年龄升序
        list.stream().sorted(
                (o1, o2) -> {
                    if (o1.getName().equals(o2.getName())) {
                        return o1.getAge() - o2.getAge();
                    } else {
                        return o1.getName().compareTo(o2.getName());
                    }
                }
        ).forEach(System.out::println);
        List sortenListDesc = list.stream().sorted(Comparator.comparing(People::getAge).reversed()).collect(Collectors.toList());

        //求和字段属性为BigDecimal时:
        BigDecimal totalCost = list.stream().map(People::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

        //返回第一个元素
        Optional first = list.stream().findFirst();
        System.out.println(first.get());
        //返回任意一个元素
        System.out.println(list.stream().findAny().get());
        //anyMatch 是否匹配任意一元素  检查是否包含名字为Tom的
        System.out.println(list.stream().anyMatch(e -> e.getName().equals("Tom")));
        //allMatch 是否匹配所有元素
        System.out.println(list.stream().allMatch(e -> e.getName().equals("Tom")));
        //noneMatch  是否未匹配所有元素
        System.out.println(list.stream().noneMatch(e -> e.getName().equals("Tom")));
        //findFirst 返回元素中第一个值
        People student = list.stream().findFirst().get();
        //findAny 返回元素中任意一个值
        People student1 = list.stream().findAny().get();
        //max 返回最大值 查询英语成绩最高的学生
        People student2 = list.stream().max((l1, l2) -> l2.getEnglish().compareTo(l1.getEnglish())).get();
        //min 最小值  将上面l1,l2位置对调
        People student3 = list.stream().max((l1, l2) -> l2.getEnglish().compareTo(l1.getEnglish())).get();


        
        Stream stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
        Stream newStream = stream.filter(s -> s > 5) //6 6 7 9 8 10 12 14 14
                .distinct() //6 7 9 8 10 12 14
                .skip(2) //9 8 10 12 14
                .limit(2); //9 8
        newStream.forEach(System.out::println);


        

        //将每个元素转成一个新的且不带逗号的元素
        Stream s1 = list.stream().map(s -> s.getName().replaceAll(",", ""));
        s1.forEach(System.out::println); // abc  123

        Stream s3 = list.stream().flatMap(s -> {
            //将每个元素转换成一个stream
            String[] split = s.getName().split(",");
            Stream s2 = Arrays.stream(split);
            return s2;
        });
        s3.forEach(System.out::println); // a b c 1 2 3
    }
    
	
    public void testReduce() {
        Stream stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8});
        //求集合元素只和
        Integer result = stream.reduce(0, Integer::sum);
        System.out.println(result);
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //求和
        stream.reduce((i, j) -> i + j).ifPresent(System.out::println);
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //求最大值
        stream.reduce(Integer::max).ifPresent(System.out::println);
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //求最小值
        stream.reduce(Integer::min).ifPresent(System.out::println);
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //做逻辑
        stream.reduce((i, j) -> i > j ? j : i).ifPresent(System.out::println);
        stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
        //求逻辑求乘机
        int result2 = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);
        Optional.of(result2).ifPresent(System.out::println);
        //拼接字符串
        String append = list.stream().map(People::getName).reduce("拼接字符串:", String::concat);
        //求平均值
        double average = list.stream().mapToInt(People::getAge).average().orElse(0.0);
        //求最大值
        int min = list.stream().map(People::getAge).reduce(Integer::min).orElse(0);
        System.out.println("min : " + min);
        //求最小值
        int max = list.stream().map(People::getAge).reduce(Integer::max).orElse(0);
        System.out.println("max : " + max);
        //四种求和的方式
        int ageSumThree = list.stream().map(People::getAge).reduce(0, Integer::sum);
        System.out.println("ageSumThree: " + ageSumThree);
        int ageSumFive = list.stream().map(People::getAge).reduce(Integer::sum).orElse(0);
        System.out.println("ageSumFive: " + ageSumFive);
        int ageSumOne = list.stream().collect(Collectors.summingInt(People::getAge));
        System.out.println("ageSumOne" + ageSumOne);
        int ageSumFour = list.stream().mapToInt(People::getAge).sum();
        System.out.println("ageSumFour: " + ageSumFour);
    }
}
collect 返回集合
//装成list
List ageList = list.stream().map(People::getAge).collect(Collectors.toList()); // [10, 20, 10]

//转成set
Set ageSet = list.stream().map(People::getAge).collect(Collectors.toSet()); // [20, 10]

//转成map,注:key不能相同,否则报错
Map studentMap = list.stream().collect(Collectors.toMap(People::getName, People::getAge)); // {cc=10, bb=20, aa=10}

//字符串分隔符连接
String joinName = list.stream().map(People::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)

//聚合操作
//1.学生总数
Long count = list.stream().collect(Collectors.counting());
//2.最大年龄 (最小的minBy同理)
Integer maxAge = list.stream().map(People::getAge).collect(Collectors.maxBy(Integer::compare)).get();
//3.所有人的年龄
Integer sumAge = list.stream().collect(Collectors.summingInt(People::getAge));
//4.平均年龄
Double averageAge = list.stream().collect(Collectors.averagingDouble(People::getAge)); // 13.333333333333334
// 带上以上所有方法
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(People::getAge));
System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());

//分组
Map> collect = list.stream().collect(Collectors.groupingBy(People::getId));
//多重分组,先根据分数分再根据年龄分
Map>> typeAgeMap = list.stream().collect(Collectors.groupingBy(People::getMath, Collectors.groupingBy(People::getAge)));

//分区
//分成两部分,一部分大于10岁,一部分小于等于10岁
Map> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));


        
reduce的介绍及用法

    Optional reduce(BinaryOperator accumulator):第一次执行时,accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推。
    T reduce(T identity, BinaryOperator accumulator):流程跟上面一样,只是第一次执行时,accumulator函数的第一个参数为identity,而第二个参数为流中的第一个元素。
     U reduce(U identity,BiFunction accumulator,BinaryOperator combiner):在串行流(stream)中,该方法跟第二个方法一样,即第三个参数combiner不会起作用。在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。

reduce参考说明

 
        //经过测试,当元素个数小于24时,并行时线程数等于元素个数,当大于等于24时,并行时线程数为16
        List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);

        Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();
        System.out.println(v);   // 300

        Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2);
        System.out.println(v1);  //310

        Integer v2 = list.stream().reduce(0,
                (x1, x2) -> {
                    System.out.println("stream accumulator: x1:" + x1 + "  x2:" + x2);
                    return x1 - x2;
                },
                (x1, x2) -> {
                    System.out.println("stream combiner: x1:" + x1 + "  x2:" + x2);
                    return x1 * x2;
                });
        System.out.println(v2); // -300

        Integer v3 = list.parallelStream().reduce(0,
                (x1, x2) -> {
                    System.out.println("parallelStream accumulator: x1:" + x1 + "  x2:" + x2);
                    return x1 - x2;
                },
                (x1, x2) -> {
                    System.out.println("parallelStream combiner: x1:" + x1 + "  x2:" + x2);
                    return x1 * x2;
                });
        System.out.println(v3); //197474048
Steam之两个list间交集、并集、差集
 public void listOpt() {
        List list1 = new ArrayList();
        list1.add("1111");
        list1.add("2222");
        list1.add("3333");

        List list2 = new ArrayList();
        list2.add("3333");
        list2.add("4444");
        list2.add("5555");

        // 交集
        List intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
        System.out.println("---得到交集 intersection---");
        intersection.parallelStream().forEach(System.out::println);

        // 差集 (list1 - list2)
        List reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
        System.out.println("---得到差集 reduce1 (list1 - list2)---");
        reduce1.parallelStream().forEach(System.out::println);

        // 差集 (list2 - list1)
        List reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
        System.out.println("---得到差集 reduce2 (list2 - list1)---");
        reduce2.parallelStream().forEach(System.out::println);

        // 并集
        List listAll = list1.parallelStream().collect(Collectors.toList());
        List listAll2 = list2.parallelStream().collect(Collectors.toList());
        listAll.addAll(listAll2);
        System.out.println("---得到并集 listAll---");
        listAll.parallelStream().forEach(System.out::println);

        // 去重并集
        List listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());
        System.out.println("---得到去重并集 listAllDistinct---");
        listAllDistinct.parallelStream().forEach(System.out::println);

        System.out.println("---原来的List1---");
        list1.parallelStream().forEach(System.out::println);
        System.out.println("---原来的List2---");
        list2.parallelStream().forEach(System.out::println);
    }
list和tree相互转换
 
    public static List list2tree(List list) {
        List result = new ArrayList<>();

        Map map = list.stream().collect(Collectors.toMap(test -> test.getId(), test -> test));
        for (Zone test : list) {
            Zone p = map.get(test.getParentId());
            if (p == null) {
                result.add(test);
            } else {
                if (p.getChildren() == null) {
                    p.setChildren(new ArrayList<>());
                }
                p.getChildren().add(test);
            }
        }
        return result;
    }

	
    public static List tree2list(List list) {
        List result = new ArrayList<>();
        for (Zone retTreePath : list) {
            List c = retTreePath.getChildren();
            result.add(retTreePath);
            if (!CollectionUtils.isEmpty(c)) {
                result.addAll(tree2list(c));
                retTreePath.setChildren(null);
            }
        }
        return result;
    }
stream流式写法把list换为Tree
 
    public static List listToTree(List zoneList) {
        Map> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(Zone::getParentId));
        zoneList.forEach(zone -> zone.setChildren(zoneByParentIdMap.get(zone.getId())));
        return zoneList.stream().filter(v -> v.getParentId().equals("0")).collect(Collectors.toList());
    }
People.java
public class People {
    private String id;
    private String name;
    private Integer age;
    private Integer math;
    private Integer english;
    private BigDecimal money;
    private List children;

    public People(String id, String name, Integer age,Integer math) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.math=math;
    }
}
Zone.java
public class Zone {

   private String id;

    private String name;

    private String parentId;

    private List children;

    public Zone(String id, String name, String parentId) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
    }

    public void addChildren(Zone zone) {
        if (children == null) {
            children = new ArrayList<>();
        }
        children.add(zone);
    }
	//get set 方法
}

参考的博客:
Java 8 stream的详细用法

JAVA stream流详细教程

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/956468.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号