java – 获取List中特定元素的数量

前端之家收集整理的这篇文章主要介绍了java – 获取List中特定元素的数量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种快速方法来查找作为一个特定元素的List元素的数量
  1. List<String> list = new ArrayList<String>();
  2. list.add("apple");
  3. list.add("banana");
  4. list.add("apple");
  5. list.add("kiwi");
  6.  
  7. // I'm looking for a method as List.amountOf(Object obj):
  8.  
  9. list.amountOf("apple"); // should return 2
  10. list.amountOf("kiwi"); // should return 1
  11. list.amountOf("pear"); // should return 0

解决方法

您可以使用Collections.frequency:
  1. int amountOfApple = Collections.frequency(list,"apple");

使用Java 8,您还可以使用流来执行此操作:

  1. long amountOfApple = list.stream().filter(s -> "apple".equals(s)).count();

猜你在找的Java相关文章