Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 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 Reply

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...