Java8 Stream 分组求和使用笔记

Java8 Stream 分组求和使用笔记

话不多说,直接贴代码,分组使用

class Foo {
    private int code;

    private int count;

    public Foo(int code, int count) {
        this.code = code;
        this.count = count;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}
public static void main(String[] args) {
        Foo foo1 = new Foo(1, 2);
        Foo foo2 = new Foo(2, 23);
        Foo foo3 = new Foo(2, 6);
        List<Foo> list = new ArrayList<>(4);
        list.add(foo1);
        list.add(foo2);
        list.add(foo3);
        Map<Integer, List<Foo>> collect = list.stream().collect(Collectors.groupingBy(Foo::getCode));
        List<Foo> list1 = collect.get(1);
        List<Foo> list2 = collect.get(2);
        list1.forEach(e -> System.out.println(e.getCode() + ":" + e.getCount()));
        System.out.println("-----------这里是分界线-----------------------------");
        list2.forEach(e -> System.out.println(e.getCode() + ":" + e.getCount()));
    }

输出结果:

1:2
-----------这里是分界线-----------------------------
2:23
2:6

分组求和使用

public static void main(String[] args) {
        Foo foo1 = new Foo(1, 2);
        Foo foo2 = new Foo(2, 23);
        Foo foo3 = new Foo(2, 6);
        List<Foo> list = new ArrayList<>(4);
        list.add(foo1);
        list.add(foo2);
        list.add(foo3);
        Map<Integer, IntSummaryStatistics> collect = list.stream().collect(Collectors.groupingBy(Foo::getCode, Collectors.summarizingInt(Foo::getCount)));
        IntSummaryStatistics statistics1 = collect.get(1);
        IntSummaryStatistics statistics2 = collect.get(2);
        System.out.println(statistics1.getSum());
        System.out.println(statistics1.getAverage());
        System.out.println(statistics1.getMax());
        System.out.println(statistics1.getMin());
        System.out.println(statistics1.getCount());

        System.out.println(statistics2.getSum());
        System.out.println(statistics2.getAverage());
        System.out.println(statistics2.getMax());
        System.out.println(statistics2.getMin());
        System.out.println(statistics2.getCount());
    }

输出结果:

2
2.0
2
2
1
29
14.5
23
6
2

stream真的是相当的好用,Mark一下,欢迎大神在评论区留下你的Stream骚操作。

猜你喜欢

转载自blog.csdn.net/u011207553/article/details/80285386