简体   繁体   English

如何使用 Java Stream 轻松实现分组条件计数

[英]How to easily implement conditional count in groupby using Java Stream

I have the following data(A class structure):我有以下数据(一个类结构):

[
  {
    "name": "a",
    "enable": true
  },
  {
    "name": "a",
    "enable": false
  },
  {
    "name": "b",
    "enable": false
  },
  {
    "name": "b",
    "enable": false
  },
  {
    "name": "c",
    "enable": false
  }
]

How can I replace the complex code below with a simple steam:如何用简单的蒸汽替换下面的复杂代码:

List<A> list = xxxxx;
Map<String, Integer> aCountMap = new HashMap<>();
list.forEach(item -> {
    Integer count = aCountMap.get(item.getName());
    if (Objects.isNull(count)) {
        aCountMap.put(item.getName(), 0);
    }
    if (item.isEnable()) {
        aCountMap.put(item.getName(), ++count);
    }
});

The correct result is as follows:正确结果如下:

{"a":1}
{"b":0}
{"c":0}

You might simply be counting the objects filtered by a condition:您可能只是在计算按条件过滤的对象:

Map<String, Long> aCountMap = list.stream()
        .filter(A::isEnable)
        .collect(Collectors.groupingBy(A::getName, Collectors.counting()));

But since you are looking for the 0 count as well, Collectors.filtering with Java-9+ provides you the implementation such as :但是由于您也在寻找0计数,Java-9+ 的Collectors.filtering为您提供了如下实现:

Map<String, Long> aCountMap = List.of().stream()
        .collect(Collectors.groupingBy(A::getName,
                Collectors.filtering(A::isEnable,
                        Collectors.counting())));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM