Map 遍历主要有两种KeySet EntrySet
第一种:KeySet
TreeMap<String,String>map=new TreeMap<>();
map.put("1","lj");
map.put("3","lll");
map.put("3","eee");
map.put("4","ewwwwwww");
//Collection<String> values = map.values();
Set<String> strings = map.keySet();
Iterator<String> iterator = strings.iterator();
while (iterator.hasNext()){
String next = iterator.next();
System.out.println(next+":"+map.get(next));
}
第二种:EntrySet
String key="";
String value="";
Map<String,String> map=new HashMap<>();
map.put("1","lj");
map.put("2","lll");
map.put("3","eee");
map.put("4","ewwwwwww");
Set<Map.Entry<String, String>> entries = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()){
Map.Entry<String, String> next = iterator.next();
key= next.getKey();
value= next.getValue();
System.out.println(key+":"+value);
}
}
第三种:java8
//根据value 排序后展示map
Map<Integer,Integer>mapp=new HashedMap();
mapp.put(1,2);
mapp.put(2,4);
mapp.put(3,7);
mapp.put(4,9);
Comparator<Map.Entry<Integer,Integer>> entryComparator = Map.Entry.comparingByValue();
Consumer<Map.Entry<Integer,Integer>> kKeyStreamingChannel = (x) -> {
System.out.println(x);
};
mapp.entrySet().stream().sorted(entryComparator).forEach(kKeyStreamingChannel);
输出:1=2 2=4 3=7 4=9
//普通循环遍历:
Consumer<Map.Entry<Integer,Integer>> kKeyStreamingChannel = (x) -> {
System.out.println(x);
};
mapp.entrySet().stream().forEach(kKeyStreamingChannel);