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}
0

1 Answer 1

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())));
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a similar approach for Java 8?
@赵彬杰 This answer shares an approach of how you can create a static method in Java-8 as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.