【问题标题】:Java-8 Get count with value in specific rangeJava-8 获取特定范围内的值的计数
【发布时间】:2019-09-09 16:27:53
【问题描述】:

我有产品列表,想查找特定成本范围内的产品数量,例如, 如果 productList 有 10 个产品的成本在 1-10 之间、50 个在 11-100 之间以及 100 个在 101-1000 之间,那么它应该返回如下的地图,

“1-10”:10 “11-100”:50 “101:1000”:100

  class Product {
        long id;
        long cost;
        String name;
        //getters setters
    }  

我尝试了很多东西,但没有奏效, 列出 productList = getProducts();

productList.stream().collect(Collectors.toMap(//logic to get map));

非常感谢任何帮助。

【问题讨论】:

    标签: java collections java-8 java-stream


    【解决方案1】:

    您可以为范围创建Function 并使用Collectors.groupingBy,如下所示,

    Map<String, Long> countByCost = productList.stream()
                    .collect(Collectors.groupingBy(costRange, TreeMap::new, Collectors.counting()));
    
    Function<Product, String> costRange = ele -> {
            if(ele.cost >= 1 && ele.cost < 11)
                return "1-10";
            if(ele.cost >= 11 && ele.cost < 101)
                return "11-100";
            if(ele.cost >= 101 && ele.cost < 1001)
                return "101-1000";
            return "others";
     };
    

    更新: Holger 建议的更优雅的成本范围函数,

    Function<Product, String> costRange = ele -> {
     if(ele.cost < 1) return "others"; 
    long i = ele.cost == 1? 1: (long)Math.pow(10, Math.floor(Math.log10(ele.cost-1))); 
    return (i|1)+"-"+(i*10); };
    

    【讨论】:

    • 不要return null,而是将它们分组为"others"
    • 完美运行。
    • 在这里使用TreeMap 有点没有意义,因为它会按字典顺序排列键,而不是按数字排列。此外,costRange 必须在使用前定义。代替if 梯形图,您可以使用通用函数,如Function&lt;Product, String&gt; costRange = ele -&gt; { if(ele.cost &lt; 1) return "others"; long i = ele.cost == 1? 1: (long)Math.pow(10, Math.floor(Math.log10(ele.cost-1))); return (i|1)+"-"+(i*10); };
    • @Holger 感谢您的宝贵反馈。在这种情况下,即使是字典顺序也会产生有效的顺序。我什至无法想到这样的 costRange 函数。这对我来说是一次很棒的学习。
    • 字典顺序为"1-10", "101-1000", "11-100",数字顺序为"1-10", "11-100", "101-1000"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多