美文网首页
Java8 Stream 之归约操作

Java8 Stream 之归约操作

作者: Tinyspot | 来源:发表于2023-11-08 12:30 被阅读0次

    1. 归约方法

    public interface Stream<T> extends BaseStream<T, Stream<T>> {
    
        Optional<T> reduce(BinaryOperator<T> accumulator);
        
        T reduce(T identity, BinaryOperator<T> accumulator);
    
        <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
    }
    

    2. collect() 的归约

    • 归约操作:将流中的元素规约为单一值(通过重复应用二元运算符)

    归约操作的工作原理:
    利用累积函数,把一个初始化为起始值的累加器
    把转换函数应用到流中每个元素上得到的结果不断迭代合并起来

    3. Integer的归约

    3.1 元素求和

    reduce()对数字流求和

    @Test
    public void patternOne() {
        List<Integer> numbers = Arrays.asList(1, 2, 3);
    
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
    
        Assertions.assertEquals(sum, 6);
    }
    
    @Test
    public void patternTwo() {
        int count = Stream.of(1, 2, 3)
                .reduce(0, (acc, element) -> acc + element);
    
        Assertions.assertEquals(count, 6);
    }
    

    展开 reduce 操作

    @Test
    public void expandReduce() {
        BinaryOperator<Integer> accumulator = (acc, element) -> acc + element;
        int count = accumulator.apply(
                accumulator.apply(
                        accumulator.apply(0, 1),
                        2),
                3);
    }
    

    3.2 计算金额

    @Test
    public void test () {
        List<OrderDTO> list = Arrays.asList(new OrderDTO("1001", 10200L), new OrderDTO("1002", 200L));
    
        Optional<Long> orderAmounts = list.stream()
                .map(OrderDTO::getOrderAmount)
                .reduce((a, b) -> a + b);
    
        Long amount = list.stream()
                .map(OrderDTO::getOrderAmount)
                .reduce(Long::sum)
                .orElse(0L);
    
        System.out.println(amount);
    }
    

    3.3 最大值和最小值

    @Test
    public void maxReduce() {
        List<Integer> numbers = Arrays.asList(10, 25, 3);
        
        // Optional<Integer> optional = numbers.stream().reduce(Integer::max);
        Integer max = numbers.stream()
                .reduce(Integer::max)
                .orElse(0);
    }
    
    @Test
    public void minReduce() {
        List<Integer> numbers = Arrays.asList(10, 25, 3);
        Integer min = numbers.stream().reduce(Integer::min)
                .orElse(0);
    }
    

    3.4 计算流中元素的个数

    把流中每个元素都映射成数字 1,然后用 reduce 求和

    @Test
    public void count() {
        List<String> menus = Arrays.asList("chicken", "duck", "sausage");
        int count = menus.stream()
                .map(d -> 1)
                .reduce(0, (a, b) -> a + b);
    
        // or menus.size()
    }
    

    map 和 reduce 的连接通常称为 map-reduce 模式
    也可用 count() 来计算个数 long count = menus.stream().count();

    相关文章

      网友评论

          本文标题:Java8 Stream 之归约操作

          本文链接:https://www.haomeiwen.com/subject/kwjqwdtx.html