我正在寻找一种快速方法来查找作为一个特定元素的List元素的数量:
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
解决方法
您可以使用Collections.frequency:
int amountOfApple = Collections.frequency(list,"apple");
使用Java 8,您还可以使用流来执行此操作:
long amountOfApple = list.stream().filter(s -> "apple".equals(s)).count();