经常会用到集合的遍历,但是还是记不住常用的遍历方法,每次都得到处去找,现在索性就都找好了放在博客里面,方便以后查阅的同时也顺带着水一篇博客。
一、map遍历
方法一:
System.out.println("通过Map.keySet遍历key和value:"); for (String key : map.keySet()) { System.out.println("key= "+ key + " and value= " + map.get(key)); }
方法二:
System.out.println("通过Map.entrySet使用iterator遍历key和value:"); Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
方法三:
System.out.println("通过Map.entrySet遍历key和value"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); }
方法四:
System.out.println("通过Map.values()遍历所有的value,但不能遍历key"); for (String v : map.values()) { System.out.println("value= " + v); }
二、set遍历
方法一:
Set<String> set = new HashSet<String>(); Iterator<String> it = set.iterator(); while (it.hasNext()) { String str = it.next(); System.out.println(str); }
方法二:
for (String str : set) { System.out.println(str); }
方法三:
Set<Object> set = new HashSet<Object>(); for (Object obj: set) { if(obj instanceof Integer){ int aa= (Integer)obj; }else if(obj instanceof String){ String aa = (String)obj } System.out.println(aa); }
三、map按照value值排序
public static HashMap sortByValue(HashMap<String, Integer> map) {//desc List list = new LinkedList(map.entrySet()); Collections.sort(list, new Comparator(){ public int compare(Object o1, Object o2) { return ((Comparable) ((Map.Entry)o2).getValue()) .compareTo(((Map.Entry)o1).getValue()); } }); LinkedHashMap result = new LinkedHashMap(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry entry = (Map .Entry) it.next(); result.put(entry.getKey(), entry.getValue()); } return result; }