项目中遇到要求统计一下数据A出现的次数,用了项目中的list()方法,查询所有,就懒得写统计语句了,查出来把数据A单独放到list里面然后使用Collections.frequency(arrayList, "A")
统计出A元素出现的次数即可。
一、贴个代码吧
@Test
public void Test(){
String str = "A,A,A,A,A,B,C,X,D,S,W,Q,Q,Q";
String[] split = str.split(",");
ArrayList<String> arrayList = new ArrayList<>(split.length);
Collections.addAll(arrayList,split);
System.out.println("A : " + Collections.frequency(arrayList, "A"));
}
其中的Collections.addAll(arrayList,split)
我是为了把数组转为list,下面为运行结果
上面知道怎么用了,知其然也要知其所以然,接下来咱们看一下它的源码:
public static int frequency(Collection<?> c, Object o) {
int result = 0;
if (o == null) {
for (Object e : c)
if (e == null)
result++;
} else {
for (Object e : c)
if (o.equals(e))
result++;
}
return result;
}
看源码可以看出它只是把循环对比封装了起了,其实也可以自己直接写,它这样只是简化了你写代码的繁琐性