Supplement on "Map traversal" of

[Problem Description] The purpose of this question is to allow everyone to master several ways Map traversal.
The first: second value, and key value by traversing Map.keySet
second: iterator traversal through the use of key and value Map.entrySet
third: through all value by Map.values (), but not traversing key

This question was Java teacher corrected many times, we look at the beginning of the questions asked. In the beginning of Java teacher requirements needed to Map descending order. If the sort, then you need to use compareTo method Comparator class. While this method is a subclass of Map TreeMap.
At that time many students say I was wrong, in fact, it is not wrong, it is a written Lambda expressions. You can refer to the following article.
Lambda expressions (1)
Lambda expressions (2)
we look at the specific operation code

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class Test_sort{
    public static void main(String[] args) {
    	//注意:这个Map的定义是从这里开始,到14行结束
    	//这里使用了public TreeMap(Comparator<? super K> comparator)构造器
        Map<String,String>map = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o2.compareTo(o1);
            }
        });

        map.put("1","Language");
        map.put("2","C Language");
        map.put("3","Java Language");

        System.out.println(map);
    }
}

Of course, if you are using Lambda expressions are more compact, we can make the following changes to the definition of the map.

	//这两种定义的方式都是相同的
	Map<String,String>map = new TreeMap<>((o1, o2) -> o2.compareTo(o1));



The above operations are difficult to see on the map the key sort, we can also sort the values of the map. But you need to use Collections.sort () method has.
Can refer to the following articles:
allows you to never again because Collections.sort () and confused (1)
so that you never because Collections.sort () and confused (2)

Published 18 original articles · won praise 8 · views 1504

Guess you like

Origin blog.csdn.net/weixin_46192593/article/details/104986263