zoukankan      html  css  js  c++  java
  • Java8 Stream

    创建无限流

    1. 迭代
    Stream<Integer> iterate = Stream.iterate(0, x -> x + 2);
    iterate.forEach(System.out::println);
    //iterate.limit(10).forEach(System.out::println);
    

    会从0开始+2的方式一直输出数据,如果只想要前10个,就加上limit。

    1. 生成
    Stream.generate(() -> Math.random()).forEach(System.out::println);
    

    无限生成随机数。

    筛选和切片(中间操作)

    多个中间操作可以连接起来形成一个流水线,除非流水线触发终止操作,否则中间操作不会执行任何处理,而在终止操作时一次性全部处理,称为“惰性求值”。

    1. distinct() 的去重是依赖 equals()hashCode()
    List<UserTest> list = new ArrayList<>();
    list.add(new UserTest(1, "李四"));
    list.add(new UserTest(1, "李四"));
    list.add(new UserTest(2, "王五"));
    list.add(new UserTest(2, "王五"));
    list.add(new UserTest(3, "赵六"));
    list.stream().distinct().forEach(System.out::println);
    

    在没有重写 UserTestequalshashCode

    UserTest{id=1, name='李四'} UserTest{id=1, name='李四'} UserTest{id=2, name='王五'} UserTest{id=2, name='王五'} UserTest{id=3, name='赵六'}
    重写`UserTest` 的 `equals` 和`hashCode` ``` @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserTest)) return false; UserTest userTest = (UserTest) o; if (id != userTest.id) return false; return name != null ? name.equals(userTest.name) : userTest.name == null; } @Override public int hashCode() { int result = id; result = 31 * result + (name != null ? name.hashCode() : 0); return result; } ``` >UserTest{id=1, name='李四'} UserTest{id=2, name='王五'} UserTest{id=3, name='赵六'}
    1. filter 接收Lambda,从流中排除某些元素

    2. limit 截断流,使其元素不超过指定个数

    3. skip 跳过元素,返回一个扔掉了前n个元素的流, 若流中元素不够n个则返回一个空流,与limit互补。

    映射(中间操作)

    1. map 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射到成一个新的元素。
    List<String> list = Arrays.asList("aaa", "nnn", "vvv");
    Stream<Stream<Character>> streamStream = list.stream().map(OperateTest::filterCharacter);
    streamStream.forEach((sm) -> sm.forEach(System.out::println));
    
    1. flatMap 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流。
    Stream<Character> characterStream = list.stream().flatMap(OperateTest::filterCharacter);
    characterStream.forEach(System.out::println);
    

    根据 mapflatMap 的返回值可以知道, map 返回的是嵌套流,flatMap 是返回一个流,打印之后的结果是一样的,map 返回的嵌套流会在后面的输出时,多次变量,而 flatMap 就很好的解决了这个问题。

    排序(中间操作)

    1. sorted() 自然排序

    2. sorted(Comparator com) 定制排序

    list.stream().sorted(Comparator.comparing(UserTest::getId).thenComparing(UserTest::getName)).forEach(System.out::println);
    

    查找与匹配(终止操作)

    1. allMatch 检查是否匹配所有元素
    boolean result = list.stream().allMatch(e -> e.getName().equals("李四"));
    System.out.println(result); // false
    
    1. anyMatch 检查是否至少匹配一个元素
    boolean result = list.stream().anyMatch(e -> e.getName().equals("李四"));
    System.out.println(result); // true
    
    1. noneMath 是否没有匹配所有元素
    boolean reuslt = list.stream().noneMatch(e -> e.getName().equals("田七"));
    System.out.println(reuslt); // true
    
    1. findFirst 返回第一个元素
    Optional<UserTest> first = list.stream().sorted(Comparator.comparing(UserTest::getId)).findFirst();
    System.out.println(first.get());
    

    按照id排序之后,返回第一个元素。

    1. findAny 返回当前流中的任意元素
    Optional<UserTest> result = list.parallelStream().filter(e -> e.getName().equals("李四")).findAny();
    System.out.println(result.get());
    
    1. count 返回元素的个数

    2. max 返回最大值

    Optional<UserTest> max = list.stream().max(Comparator.comparing(UserTest::getId));
    System.out.println(max);
    
    1. min 返回最小值
    Optional<Integer> min = list.stream().map(UserTest::getId).min(Integer::compareTo);
    System.out.println(min);
    

    归约(终止操作)

    1. reduce(T identity, BinaryOperator) / reduce(BinaryOperator) 可以将流中元素反复结合起来,返回一个值
    Integer reduce = list.stream().map(UserTest::getId).reduce(0, (x, y) -> x + y);
    System.out.println(reduce);
    
    Optional<Integer> reduce = list.stream().map(UserTest::getId).reduce(Integer::sum);
    System.out.println(reduce.get());
    

    使用 mapreduce

    List<UserTest> list = new ArrayList<>();
    list.add(new UserTest(1, "李四"));
    list.add(new UserTest(1, "李四"));
    list.add(new UserTest(2, "王五"));
    list.add(new UserTest(2, "王五"));
    list.add(new UserTest(3, "赵六"));
    Optional<Integer> reduce = list.stream().map(UserTest::getId).reduce(Integer::sum);
    System.out.println(reduce.get());
    

    收集(终止操作)

    collect(Collector c) 将流转换成其他形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法

    1. toList() 返回list集合

    2. toSet() 返回set集合

    3. toCollection(HashSet::new)

    4. counting() 获取总数

    5. averagingInt(ToIntFunction mapper) 获取平均值

    Double collect = list.stream().collect(Collectors.averagingInt(UserTest::getId));
    
    1. summingInt(ToIntFunction mapper) 获取总和
    Integer collect = list.stream().collect(Collectors.summingInt(UserTest::getId));
    
    1. maxBy 最大值(不建议使用,建议直接使用上面的max())
    Optional<UserTest> collect = list.stream().collect(Collectors.maxBy(Comparator.comparing(UserTest::getId)));
    
    1. groupingBy 分组
    Map<Integer, List<UserTest>> collect = list.stream().collect(Collectors.groupingBy(UserTest::getId));
    
    1. partitioningBy 分区
    Map<Boolean, List<UserTest>> collect = list.stream().collect(Collectors.partitioningBy(e -> e.getId() > 3));
    System.out.println(collect);
    

    输出

    {false=[UserTest{id=1, name='李四'}, UserTest{id=2, name='王五'}, UserTest{id=1, name='李四'}, UserTest{id=3, name='赵六'}], true=[UserTest{id=5, name='王五'}]}

  • 相关阅读:
    MVC之Ajax异步操作
    MVCHtmlHelper使用
    Xamarin.Forms初始
    .NET CORE2.0后台管理系统(一)配置API
    DDD领域驱动之干货(四)补充篇!
    基于官方驱动封装mongodb
    webApi签名验证
    在.Net下使用redis基于StackExchange.Redis
    DDD领域驱动之干货(三)完结篇!
    DDD领域驱动之干货(二)
  • 原文地址:https://www.cnblogs.com/Godfunc/p/9210004.html
Copyright © 2011-2022 走看看