草庐IT

Java8用Stream流一行代码实现数据分组统计,排序,最大值、最小值、平均值、总数、合计

小黑孩. 2023-08-10 原文

Java8对数据处理可谓十分流畅,既不改变数据,又能对数据进行很好的处理,今天给大家演示下,用Java8的Stream如何对数据进行分组统计,排序,求和等

汇总统计方法

找到汇总统计的方法。这些方法属于java 8的汇总统计类。
getAverage(): 它返回所有接受值的平均值。
getCount(): 它计算所有元素的总数。
getMax(): 它返回最大值。
getMin(): 它返回最小值。
getSum(): 它返回所有元素的总和。

示例:统计用户status的最大值,最小值,求和,平均值

看官可以根据自己的需求进行灵活变通

    @GetMapping("/list")
    public void list(){
        List<InputForm> inputForms = inputFormMapper.selectList();
        Map<String, IntSummaryStatistics> collect = inputForms.stream()
            .collect(Collectors.groupingBy(InputForm::getCreateUserName, Collectors.summarizingInt(InputForm::getStatus)));

        // 对名字去重
        Set<String> collect1 = inputForms.stream().distinct().map(InputForm::getCreateUserName).collect(Collectors.toSet());

        // 遍历名字,从map中取出对应用户的status最大值,最小值,平均值。。。
        for (String s1 : collect1) {
            IntSummaryStatistics statistics1 = collect.get(s1);

            System.out.println("第一个用户的名字为====" + s1);
            System.out.println("**********************************************");
            System.out.println("status的个数为===" + statistics1.getCount());
            System.out.println("status的最小值为===" + statistics1.getMin());
            System.out.println("status的求和为===" + statistics1.getSum());
            System.out.println("status的平均值为===" + statistics1.getAverage());
            System.out.println();
            System.out.println();
        }
    }

  结果如下:

分组统计:

    @GetMapping("/list")
    public void list(){
        List<InputForm> inputForms = inputFormMapper.selectList();
        System.out.println("inputForms = " + inputForms);

        Map<String, Long> collect = inputForms.stream().collect(Collectors.groupingBy(InputForm::getCreateUserName,
            Collectors.counting()));
        
        System.out.println("collect = " + collect);
    }

其中Collectors.groupingBy(InputForm::getCreateUserName, Collectors.counting())返回的是一个Map集合,InputForm::getCreateUserName代表key,Collectors.counting()代表value,我是按照创建人的姓名进行统计

 

可以看到总共有九条数据,其中莫昀锦有两个,周亚丽有七个

如果我们想看某个部门下面有哪些数据,可以如下代码

    @GetMapping("/list")
    public Map<String, List<InputForm>> list(){
        List<InputForm> inputForms = inputFormMapper.selectList();
        System.out.println("inputForms = " + inputForms);

        Map<String, List<InputForm>> collect = inputForms.stream()
            .collect(Collectors.groupingBy(InputForm::getCreateCompanyName));

        return collect;
    }

 求最大值,最小值

    @GetMapping("/list")
    public Map<String, List<InputForm>> list(){
        List<InputForm> inputForms = inputFormMapper.selectList();
        System.out.println("inputForms = " + inputForms);

        Optional<InputForm> min = inputForms.stream()
            .min(Comparator.comparing(InputForm::getId));

        System.out.println("min = " + min);
        return null;
    }

可以看到此id是最小的,最大值雷同

对某个字段求最大,最小,求和,统计,计数

    @GetMapping("/list")
    public void list(){
        List<InputForm> inputForms = inputFormMapper.selectList();
        System.out.println("inputForms = " + inputForms);

        IntSummaryStatistics collect = inputForms.stream()
            .collect(Collectors.summarizingInt(InputForm::getStatus));
        double average = collect.getAverage();
        int max = collect.getMax();
        int min = collect.getMin();
        long sum = collect.getSum();
        long count = collect.getCount();
        
        System.out.println("collect = " + collect);
    }

求最大值,最小值还可以这样做

        // 求最大值
        Optional<InputForm> max = inputForms.stream().max(Comparator.comparing(InputForm::getAgency));
        if (max.isPresent()){
            System.out.println("max = " + max);
        }

        // 求最小值
        Optional<InputForm> min = inputForms.stream().min(Comparator.comparing(InputForm::getAgency));
        if (min.isPresent()){
            System.out.println("min = " + min);
        }

对某个字段求和并汇总

int sum = inputForms.stream().mapToInt(InputForm::getStatus).sum();
        System.out.println("sum = " + sum);

求某个字段的平均值

        // 求某个字段的平均值
        Double collect2 = inputForms.stream().collect(Collectors.averagingInt(InputForm::getStatus));
        System.out.println("collect2 = " + collect2);
        
        // 简化后
        OptionalDouble average = inputForms.stream().mapToDouble(InputForm::getStatus).average();
        if (average.isPresent()){
            System.out.println("average = " + average);
        }

拼接某个字段的值,可以设置前缀,后缀或者分隔符

        // 拼接某个字段的值,用逗号分隔,并设置前缀和后缀
        String collect3 = inputForms.stream().map(InputForm::getCreateUserName).collect(Collectors.joining(",", "我是前缀", "我是后缀"));
        System.out.println("collect3 = " + collect3);

根据部门进行分组,并获取汇总人数

        // 根据部门进行汇总,并获取汇总人数
        Map<String, Long> collect4 = inputForms.stream().collect(Collectors.groupingBy(InputForm::getCreateDeptName, Collectors.counting()));
        System.out.println("collect4 = " + collect4);

根据部门和是否退休进行分组,并汇总人数

        // 根据部门和是否退休进行分组,并汇总人数
        Map<String, Map<Integer, Long>> collect5 = inputForms.stream().collect(Collectors.groupingBy(InputForm::getCreateDeptName, Collectors.groupingBy(InputForm::getIsDelete, Collectors.counting())));
        System.out.println("collect5 = " + collect5);

根据部门和是否退休进行分组,并取得每组中年龄最大的人

        // 根据部门和是否退休进行分组,并取得每组中年龄最大的人
        Map<String, Map<Integer, InputForm>> collect6 = inputForms.stream().collect(
            Collectors.groupingBy(InputForm::getCreateDeptName,
                Collectors.groupingBy(InputForm::getIsDelete,
                    Collectors.collectingAndThen(
                        Collectors.maxBy(
                            Comparator.comparing(InputForm::getAge)), Optional::get))));
        System.out.println("collect6 = " + collect6);

有关Java8用Stream流一行代码实现数据分组统计,排序,最大值、最小值、平均值、总数、合计的更多相关文章

  1. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  2. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  3. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  4. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  5. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  6. ruby-on-rails - 浏览 Ruby 源代码 - 2

    我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru

  7. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  8. ruby - 寻找通过阅读代码确定编程语言的ruby gem? - 2

    几个月前,我读了一篇关于ruby​​gem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:

  9. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  10. ruby - Net::HTTP 获取源代码和状态 - 2

    我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur

随机推荐