统计List数组元素中,每个元素出现的次数
1、建立Map对象,key为数组的关键字,value为该关键字出现的次数。
2、循环遍历数组,在Map中查找关键字,如果没有就put进Map中,同时value值加1。如果有Map中有该元素,说明已经put过了,则直接value值计数加1。
3、最终得到的Map对象即为各元素出现的次数。
public Map<String,Integer> countList (List<String> reslist){
Map<String,Integer> countmap = new HashMap<String, Integer>();
for(int i=0; i<reslist.size(); i++){
//在Map中查找关键字,如果没有就put进Map中,同时value值加1
if(null==countmap.get(reslist.get(i))){
countmap.put(reslist.get(i), 1);
}else{ //如果有Map中有该元素,说明已经put过了,则直接value值计数加1
countmap.put(reslist.get(i), countmap.get(reslist.get(i))+1);
}
}
return countmap;
}