0

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}
Tran Ho
  • 1,442
  • 9
  • 15
赵彬杰
  • 43
  • 4

1 Answers1

3

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())));
Naman
  • 27,789
  • 26
  • 218
  • 353