HashMap遍歷與按key排序。
阿新 • • 發佈:2019-01-22
Google搜尋 hashmap 遍歷 寫道
第一種:
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
效率高,以後一定要使用此種方式!
第二種:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低,以後儘量少使用!
map_Data.put("A", "98");
map_Data.put("B", "50");
map_Data.put("C", "50");
map_Data.put("D", "25");
map_Data.put("E", "85");
System.out.println(map_Data);
List<Map.Entry<String, String>> list_Data = new ArrayList<Map.Entry<String, String>>(map_Data.entrySet()); Collections.sort(list_Data, new Comparator<Map.Entry<String, String>>()
{
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
{
if(o2.getValue()!=null&&o1.getValue()!=null&&o2.getValue().compareTo(o1.getValue())>0){
return 1;
}else{
return -1;
}
}
});
System.out.println(list_Data); 主要的一個知識點在這個Collections.sort(list,Comparator介面實現)地方,而最最重要核心部分是這個Comparator實現。因為Comparator實現決定你的排序。採用了隱藏類實現方式。
第一種:
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
效率高,以後一定要使用此種方式!
第二種:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object val = map.get(key);
}
效率低,以後儘量少使用!
關於hashmap 按value排序
map_Data.put("A", "98");
map_Data.put("B", "50");
map_Data.put("C", "50");
map_Data.put("D", "25");
map_Data.put("E", "85");
System.out.println(map_Data);
List<Map.Entry<String, String>> list_Data = new ArrayList<Map.Entry<String, String>>(map_Data.entrySet()); Collections.sort(list_Data, new Comparator<Map.Entry<String, String>>()
{
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)
{
if(o2.getValue()!=null&&o1.getValue()!=null&&o2.getValue().compareTo(o1.getValue())>0){
return 1;
}else{
return -1;
}
}
});
System.out.println(list_Data); 主要的一個知識點在這個Collections.sort(list,Comparator介面實現)地方,而最最重要核心部分是這個Comparator實現。因為Comparator實現決定你的排序。採用了隱藏類實現方式。