package com.practice.demo;
import java.util.ArrayList;
import java.util.List;
/**
* 统计集合中指定元素出现的次数
*
* @author Janny
*
*/
public class Practice5 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("a");
list.add("a");
list.add("b");
list.add("b");
list.add("c");
list.add("d");
list.add("d");
list.add("d");
list.add("d");
list.add("d");
System.out.println(frequency(list, "a")); // 3
System.out.println(frequency(list, "b")); // 2
System.out.println(frequency(list, "c")); // 1
System.out.println(frequency(list, "d")); // 5
System.out.println(frequency(list, "xxx")); // 0
}
private static int frequency(List<String> list, String string) {
int count = 0;
for (int i = 0; i < list.size(); i++) {
if (string.equals(list.get(i))) {
count++;
}
}
return count;
}
}
|
|