本文共 1780 字,大约阅读时间需要 5 分钟。
注意:
1.Map的排序只写了按照Key排序的。
2.Map的四种遍历,前三种遍历了Key和Value,后一种只遍历Value。
package com.onlinetest;import java.util.*;/** * Map集合的排序和遍历 */public class HuaWeiTest11 { public static void main(String[] args) {// Mapmap=new HashMap<>(); Map map=new TreeMap<>(); map.put("cthree","NO3"); map.put("btwo","NO2"); map.put("aone","NO1"); map.put("dfour","NO4"); //对map按照key升序排序 sortMapByKey(map,true);// 1、新循环遍历key和value for(String key:map.keySet()){ System.out.println("新循环遍历key和value:"+key+" "+map.get(key)); }// 2.迭代器历key和value Iterator > iterator=map.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry entry=iterator.next(); System.out.println("迭代器遍历key和value:"+entry.getKey()+" "+entry.getValue()); }// 3.Entry遍历key和value for(Map.Entry entry:map.entrySet()){ System.out.println("Entry遍历key和value:"+entry.getKey()+" "+entry.getValue()); }// 4.遍历value for(String value:map.values()){ System.out.println(value); } } public static Map sortMapByKey(Map map, final boolean isRise) { if (map == null || map.isEmpty()) { return null; } Map sortMap = new TreeMap<>(new Comparator () { @Override public int compare(String s1, String s2) { if (isRise) { // 升序 return s1.compareTo(s2); } else { // 降序 return s2.compareTo(s1); } } }); sortMap.putAll(map); return sortMap; }}输出:新循环遍历key和value:aone NO1新循环遍历key和value:btwo NO2新循环遍历key和value:cthree NO3新循环遍历key和value:dfour NO4迭代器遍历key和value:aone NO1迭代器遍历key和value:btwo NO2迭代器遍历key和value:cthree NO3迭代器遍历key和value:dfour NO4Entry遍历key和value:aone NO1Entry遍历key和value:btwo NO2Entry遍历key和value:cthree NO3Entry遍历key和value:dfour NO4NO1NO2NO3NO4
转载地址:http://frpqb.baihongyu.com/