记录:根据value对Map进行排序
public class t1 {
public static void main(String[] args) {
String[] A = {"i am a coder", "Coder Coder", "Code"}; // 统计coder的个数并且 根据含有个数的字符串排序
int n = A.length;
// 找出来并且排序
Map<Integer, Integer> map = new TreeMap<>();
int count = 0;
int res;
int idx = 0;
for (String s : A){
res = 0;
String[] s1 = s.split(" ");
for (String s2 : s1){
// 统计一个字符串里面有多少个coder
if (s2.toLowerCase().equals("coder")) res++;
}
if (res == 0) idx++;
map.put(count++, res);
// map.put(res, count++);
}
Map<Integer, Integer> newMap = sortMap(map);
String[] outputArr= new String[n - idx];
count = 0;
for (int i : newMap.keySet()){
int val = newMap.get(i);
if (val == 0) continue;;
outputArr[count++] = A[i];
}
System.out.println(newMap); // outputArr也是最终的结果
}
public static Map<Integer, Integer> sortMap(Map<Integer, Integer> map){
Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
ArrayList<Map.Entry<Integer, Integer>> entryArrayList = new ArrayList<>(map.entrySet());
Collections.sort(entryArrayList, new MyNewComparator2());
Iterator<Map.Entry<Integer, Integer>> iter = entryArrayList.iterator();
Map.Entry<Integer, Integer> tmpEntry = null;
while (iter.hasNext()){
tmpEntry = iter.next();
sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
}
return sortedMap;
}
}
class MyNewComparator2 implements Comparator<Map.Entry<Integer, Integer>> { @Override public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return o2.getValue() - o1.getValue();
}
} 记录
#笔经#