问题:
代码:
package map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class SortMap {
public static void main(String[] args) {
HashMap<String, String> srcMap = new HashMap<String, String>();
srcMap.put("type0", "3");
srcMap.put("type1", "0");
srcMap.put("type4", "0");
srcMap.put("type5", "2");
srcMap.put("type3", "2");
srcMap.put("type2", "2");
HashMap<String, KeyCountInfo> sortMap = new HashMap<String, KeyCountInfo>();
for (String key : srcMap.keySet()) {
String value = srcMap.get(key);
int count = 0;
KeyCountInfo countInfo = sortMap.get(value);
if (null != countInfo) {
count = countInfo.count;
} else {
countInfo = new KeyCountInfo();
}
countInfo.addKey(key);
countInfo.setCount((count + 1));
sortMap.put(value, countInfo);
}
List<String> list = new ArrayList<String>(sortMap.keySet());
Collections.sort(list);
String keyMin = list.get(0);
String keyMax = list.get(list.size() - 1);
System.out.println("MinValue:" + keyMin + ";" + sortMap.get(keyMin));
System.out.println("MaxValue:" + keyMax + ";" + sortMap.get(keyMax));
}
public static class KeyCountInfo {
List<String> keys = new ArrayList<String>();
int count;
public void addKey(String key) {
this.keys.add(key);
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Keys:" + keys.toString() + " count:" + count;
}
}
}
运行:
MinValue:0;Keys:[type1, type4] count:2
MaxValue:3;Keys:[type0] count:1