Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

How to count number of occurrences of more than one elements in a list using Java 8 Stream or collections framework

If we have an ArrayList in Java, as follows:

ArrayList<String> animals = new ArrayList<String>();
animals.add("bat");
animals.add("bat");
animals.add("owl");
animals.add("bat");
animals.add("parrot");
animals.add("owl");
animals.add("owl");
animals.add("bat");

How can we get count of only "bat" and "owl" from this list using Java 8 Stream API / Collections in single iteration?

question from:https://stackoverflow.com/questions/65913927/how-to-count-number-of-occurrences-of-more-than-one-elements-in-a-list-using-jav

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
    Set<String> itemToFilter = Stream.of("bat", "owl")
                                    .collect(Collectors.toCollection(HashSet::new));

    Map<String, Long> result = animals.stream()
                                    .filter(animal  -> itemToFilter.contains(animal))
                                    .collect(Collectors.groupingBy(animal -> animal , Collectors.counting()));

    System.out.println("result ="+ result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...