有时候需要对map进行排序,什么会进行对map的遍历,以下是对map的遍历的方法。欢迎指正。
?package TEST; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; /** * @author Administrator * */ public class TraversalMap { public static void main(String[] args) { Map<Object, Object> map = buildMap(); // TraversalMap1(map); // TraversalMap2(map); TraversalMap3(map); // TraversalMap4(map); } /** * @return map */ public static Map<Object, Object> buildMap(){ Map<Object, Object> map = new HashMap<Object, Object>(); map.put("王力宏", "你不知道的事"); map.put("梁静茹", "可惜不是你 "); map.put("凤凰传奇", "荷塘月色"); map.put("王菲", "红豆"); map.put("周杰伦", "半兽人"); map.put("邓丽君", "好久不见"); return map; } public static void TraversalMap1(Map<Object, Object> map){ Set<Object> set = map.keySet(); Iterator<Object> it = set.iterator(); while(it.hasNext()){ Object o_key = it.next(); System.out.println("map : <key : "+o_key+"--value : "+map.get(o_key)+">"); } } /** * @param map * 得到map的values */ public static void TraversalMap2(Map<Object, Object> map){ Collection<Object> c = map.values(); Iterator<Object> it = c.iterator(); while(it.hasNext()){ Object o_key = it.next(); System.out.println("map : <key : "+"****"+"--value : "+o_key+">"); } } /**使用Map.Entry得到这一个map,然后分离出key和values * @param map */ public static void TraversalMap3(Map<Object, Object> map){ Set<Entry<Object,Object>> set = map.entrySet(); Iterator<Entry<Object, Object>> it = set.iterator(); while(it.hasNext()){ Entry<Object, Object> map_entry = it.next(); System.out.println("map : <key : "+map_entry.getKey()+"--value : "+map_entry.getValue()+">"); } } /** * 简单点的 * @param map */ public static void TraversalMap4(Map<Object, Object> map){ for(Object o: map.values()){ System.out.println("map : <key : "+getKey(map, o)+"--value : "+o+">"); } } /** * 根据value得到key * @param Map * @param Object */ public static Object getKey(Map<Object, Object> map,Object value){ Set<Object> set = map.keySet(); Iterator<Object> it = set.iterator(); while(it.hasNext()){ Object temp_o = it.next(); if(map.get(temp_o).equals(value)){ return temp_o; } } return null; } }?