在平常的工作场景下,也许我们有这样的需求场景:可能需要MAP中的key按照我们插入的顺序输出,可能需要MAP的key进行排序后输出,可能对输出的顺序无所谓,下面不多说,直接上实例:
import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class MapTest { public static void main(String[] args) { Map<String,String> testHashMap = new HashMap<String,String>(); testHashMap.put("2", "11"); testHashMap.put("1", "22"); testHashMap.put("6", "33"); testHashMap.put("4", "44"); testHashMap.put("3", "33"); testHashMap.put("9", "44"); testHashMap.put("8", "33"); testHashMap.put("7", "44"); Set<String> testHashSet = testHashMap.keySet(); System.out.println("---随机输出---"); for(String strHash : testHashSet){ System.out.println(strHash + "-" + testHashMap.get(strHash)); } Map<String,String> testTreeMap = new TreeMap<String,String>(); testTreeMap.put("2", "11"); testTreeMap.put("1", "22"); testTreeMap.put("6", "33"); testTreeMap.put("4", "44"); Set<String> testTreeSet = testTreeMap.keySet(); System.out.println("---排序输出---"); for(String strTree : testTreeSet){ System.out.println(strTree + "-" + testTreeMap.get(strTree)); } Map<String,String> testLinkedHashMap = new LinkedHashMap<String,String>(); testLinkedHashMap.put("2", "11"); testLinkedHashMap.put("1", "22"); testLinkedHashMap.put("6", "33"); testLinkedHashMap.put("4", "44"); Set<String> testLinkedHashSet = testLinkedHashMap.keySet(); System.out.println("---按插入顺序输出---"); for(String strLinkedHash : testLinkedHashSet){ System.out.println(strLinkedHash + "-" + testLinkedHashMap.get(strLinkedHash)); } } }
输出内容如下:
---随机输出--- 3-33 2-11 1-22 7-44 6-33 4-44 9-44 8-33 ---排序输出--- 1-22 2-11 4-44 6-33 ---按插入顺序输出--- 2-11 1-22 6-33 4-44