Initialize a map
| 12345 |
map<string, string> Map = < /code>new hashmap<string, string> (); map.put ( , "hell" map.put ( , "Hello" map.put ( , "hel" map.put ( , "Hello" |
1, the first way, the general use of
| 1234 |
Set<String> keySet = map.keySet();for(String key : keySet) { System.out.println("key= " + key + " and value= "+ map.get(key));} |
2, the second way, the capacity of the recommended use of large
| 12345 |
Set<Map.Entry<String,String>> entySet = map.entrySet();for(Map.Entry<String, String> entry : entySet) { System.out.println("key= "+ entry.getKey() + " and value= " + entry.getValue());} |
The experiment found that the order of the output is chaotic, a sequence bar
1. Sort by key value
First write a sort class
| 1234567 |
privatestaticclassKeyComparator implements Comparator<Map.Entry<String, String>> { publicintcompare(Map.Entry<String, String> m, Map.Entry<String, String> n) { returnm.getKey().compareTo(n.getKey()); }} |
Put the data in the list to use
| 123456789 |
list<map.entry<string, string>> list = new arraylist <map.entry<string, string>> (); list.addall (Map.entryset ()); keycomparator KC = new keycomparator (); collections.sort (list, KC); for (iterator<map.entry<string, String >> it = List.iterator (); It &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; .hasnext ();) { &NBSP;&NBSP;&NBSP;&NBSP; system.out.println ( It.next ()); |
2. Sort by value
| 1234567 |
privatestaticclassValueComparator implements Comparator<Map.Entry<String, String>> { publicintcompare(Map.Entry<String, String> m, Map.Entry<String, String> n) { returnm.getValue().compareTo(n.getValue()); }} |
Sort output
| 12345678 |
list.clear();list.addAll(map.entrySet());ValueComparator vc = newValueComparator();Collections.sort(list, vc);for(Iterator<Map.Entry<String, String>> it = list.iterator(); it.hasNext();) { System.out.println(it.next());} |
Tips: If you have any errors, please indicate that I will revise them in time.
Two ways to traverse a map (with sort)