A method for sorting and according to the key value of the Map

According to key

It requires the compareTo () method and Comparator TreeMap class.

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

public class Test_sort{
    public static void main(String[] args) {
        Map<String,String>map = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                //降序
                //return o2.compareTo(o1);
                //升序
                return o1.compareTo(o2);
            }
        });

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

        System.out.println(map);
    }
}

Among them, the definition map of Lambda expressions can be written as

		Map<String,String>map = new TreeMap<>((o1, o2) -> {
            //降序
            //return o2.compareTo(o1);
            //升序
            return o1.compareTo(o2);
        });

According to the value

Requires the Collections.sort () and Lambda Expressions
Lambda expressions. 1
Lambda Expression 2

import java.util.*;

public class Test_sort {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();

        map.put("A", "33");
        map.put("B", "31");
        map.put("C", "35");

        List<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                //升序
                return compare;
            	//降序
            	//return -compare;
            }
        });

        for (Map.Entry<String, String> maps : list) {
            System.out.println(maps.getKey() + " " + maps.getValue());
        }
    }
}

Such operations are not actually sort map itself, change the order of the list.

Published 19 original articles · won praise 8 · views 1660

Guess you like

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