public static void main(String[] args) {
String[] arr = {"ab","ab","ab","ac","ab","ac","ds","sdf","sdf","sdf","sdf","sdf","sdf","sdf"};
//创建map key保存字符串 value 保存出现的次数
Map
for (int i = 0; i < arr.length; i++) {//循环数组
if(map.containsKey(arr[i])){//判断如果key中已存在该字符串
map.put(arr[i], map.get(arr[i])+1);//value值 加一次(多出现一次)
}else{
map.put(arr[i], 1);//如果该字符串没有出现 map新保存一组数据 出现次数为1次
}
}
//循环结束
//迭代map
Set
Iterator
while (it.hasNext()) {
String key = (String) it.next();
System.out.println(key+"出现的次数为"+" "+map.get(key)+"次");
}
}
控制台输出结果
可以用map进行统计,单词作为key出现的次数作为value
publicstaticvoidmain(String[]args){intarray[]={5,10,10,5,2,5,3,5,10,5,2,5,5,10,1,5,1};Arrays.sort(array);//给数组排序intcount=0;inttmp=array[0];Mapmap=newHashMap();for(inti=0;ikey=map.keySet();for(Iteratorit=key.iterator();it.hasNext();){Integers=(Integer)it.next();System.out.println(s+"出现了"+map.get(s));}}publicstaticMapsortByValue(Mapmap){Listlist=newLinkedList(map.entrySet());Collections.sort(list,newComparator(){//将链表按照值得从小到大进行排序publicintcompare(Objecto1,Objecto2){return((Comparable)((Map.Entry)(o2)).getValue()).compareTo(((Map.Entry)(o1)).getValue());}});Mapresult=newLinkedHashMap();for(Iteratorit=list.iterator();it.hasNext();){Map.Entryentry=(Map.Entry)it.next();result.put(entry.getKey(),entry.getValue());}returnresult;}
用map就可以啊,key作为单词,value作为出现的次数
// 遍历集合
Set
for (String key : keys) {
System.out.println(key+"="+map.get(key));
}
foreach遍历即可