Map<Integer ,Object> map = new HashMap<Integer,Object>(); for(int i = 0; i<=100;i++){ map.put(i,i); } Iterator<Entry<Integer, Object>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer ,Object> entry = (Entry<Integer ,Object>)iterator.next(); Object key = entry.getKey(); Object value = entry.getValue(); }
第一種:
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 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排序
最近開發中用到了HashMap ,而且想到要利用其value的大小排序。。真是個傷腦筋的問題。
還好,經過查閱各個地方的資料。發現這個下邊的代碼處理是最簡單有效的。代碼很少,卻達到目的了。
一般我堅持的一個原則的是:能簡單處理的,盡量不做復雜工作。
關鍵代碼部分如下:
HashMap map_Data=new HashMap();
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());
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);
{
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實現