今天突然碰见一个关于Java中对map的Value进行排序的习题,在这种问题上,Python是秒杀Java的,比如python是这样的:
word = {'123':3,'456':2,'hehsadfasd':4}
sorted(word.items(),key=lambda (word,c):c,reverse=True)
[('hehsadfasd', 4), ('123', 3), ('456', 2)]
而Java却要非常多的重写方法:
public class exercise4 {
public static void main(String[] args) throws IOException {
FileReader fReader = new FileReader("222.txt");
BufferedReader bReader = new BufferedReader(fReader);
List<String> list = new ArrayList<String>();
String string = "";
while ((string = bReader.readLine()) != null) {
String l[] = string.split(" ");
for (int i = 0; i < l.length; i++) {
list.add(l[i]);
}
}
// ----------------1------------------
HashSet<String> hashSet = new HashSet<String>(list);
System.out.println(hashSet.size());
// -----------------2-------------------
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (String s : list) {
if (!map.containsKey(s))
map.put(s, 1);
else {
int num = map.get(s);
map.put(s, num + 1);
}
}
int num = 0;
for (Integer I : map.values())
if (I == 1)
num++;
// System.out.println(num);
// ---------------3------------------
System.out.println(map);
ValueComparator vc = new ValueComparator(map);
TreeMap<String, Integer> sorted_map = new TreeMap<String, Integer>(vc);
sorted_map.putAll(map);
System.out.println(sorted_map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Integer> map;
public ValueComparator(Map<String, Integer> map) {
super();
this.map = map;
}
@Override
public int compare(String o1, String o2) {
if (map.get(o1) >= map.get(o2))
return -1;
else
return 1;
}
}
这样,各位同行们,转Python吧。。。