/*
* (2)定义方法统计集合中指定元素出现的次数,如"a" 3,"b" 2,"c" 1
*/
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");
//String[] str = list.toArray(new String[list.size()]);
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
}
// 参数类型int 参数列表List<String> list,String s
@SuppressWarnings("rawtypes")
public static int frequency(List list, String s) {
Iterator it = list.iterator(); // 根据传入的集合(老集合)获取迭代器
int count = 0;
while (it.hasNext()) {
String s1= (String) it.next();// 记住每一个元素
if (s1.contains(s)) {
count++;
}
}
return count;// 返回数组元素个数
}
}
|
|