Java – gets the number of specific elements in the list

I'm looking for a quick way to find the number of list elements as a specific element:

List<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
list.add("apple");
list.add("kiwi");

// I'm looking for a method as List.amountOf(Object obj):

list.amountOf("apple");     // should return 2
list.amountOf("kiwi");      // should return 1
list.amountOf("pear");      // should return 0

Solution

You can use collections frequency:

int amountOfApple = Collections.frequency(list,"apple");

With Java 8, you can also use streams to do this:

long amountOfApple = list.stream().filter(s -> "apple".equals(s)).count();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>