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}
Naman :

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 :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334508&siteId=1