1

Assume I have a class called Combination that consists of two fields whoose type is a simple enum value.

Examples:

new Combination(Animal.DOG, Animal.CAT),

new Combination(Animal.CAT, Animal.APE),

new Combination(Animal.MOUSE, Animal.DOG)

I have a collection of combinations and I'd like to count the total occurences of each animal so that the example output would look like:

DOG=2
CAT=2
MOUSE=1
APE=1

I already tried different approches, but I didn't found a solution yet. Is there any simple way to do this in java 8?

Thanks in advance.

3
  • you can start with for loop to get the idea of an algorithm Commented Feb 16, 2017 at 20:32
  • What are the accessors for Combination? Commented Feb 16, 2017 at 20:33
  • What are the different approaches that you tried? Commented Feb 16, 2017 at 20:35

1 Answer 1

3

Here's one way:

Map<Animal, Long> counts = combinations.stream()
        .flatMap(c -> Stream.of(c.getFirst(), c.getSecond()))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Alternatively:

Map<Animal, Long> counts = Stream.concat(
            combinations.stream().map(Combination::getFirst),
            combinations.stream().map(Combination::getSecond))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Sign up to request clarification or add additional context in comments.

Comments

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.