Java8 对Map(key/value)排序后取TopN

import com.alibaba.fastjson.JSON;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Hello world!
 *
 */
public class App {
    public static void main( String[] args ) {
        Map mapRepeat = new HashMap<>();
        mapRepeat.put("aa", 1);
        mapRepeat.put("bb", 45);
        mapRepeat.put("cc", 32);
        mapRepeat.put("dd", 226);
        mapRepeat.put("ee", 16);
        mapRepeat.put("ff", 320);
        mapRepeat.put("gg", 99);

        // 1.8以后 使用lambda表达式和Stream处理
        // 1.对Map的value进行降序排序,并取前5个key
        List mobileList = mapRepeat.entrySet().stream()
                .sorted((Map.Entry e1, Map.Entry e2) -> e2.getValue() - e1.getValue())
                .map(entry -> entry.getKey()).collect(Collectors.toList())
                .subList(0, 5);
        System.out.println(JSON.toJSONString(mobileList));


        // 2、正向对Map的value排序并将结果输出到LinkedHashMap
        final Map sortedByCount1 = mapRepeat.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        System.out.println(JSON.toJSONString(sortedByCount1));

        // 3、反向 reversed对Map的value排序并将结果输出到LinkedHashMap
        final Map sortedByCount2 = mapRepeat.entrySet()
                .stream()
                .sorted((Map.Entry.comparingByValue().reversed()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        System.out.println(JSON.toJSONString(sortedByCount2));


        // 4.正向 Comparator 对Map的value排序并将结果输出到LinkedHashMap
        final Map sortedByCount3 = mapRepeat.entrySet()
                .stream()
                .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        System.out.println(JSON.toJSONString(sortedByCount3));


        //反向 Comparator 对Map的value排序并将结果输出到LinkedHashMap
        final Map sortedByCount4 = mapRepeat.entrySet()
                .stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        System.out.println(JSON.toJSONString(sortedByCount4));

        // 1.8以前
        List> list1 = new ArrayList<>();
        list1.addAll(mapRepeat.entrySet());
        Collections.sort(list1, new Comparator>() {
            @Override
            public int compare(Map.Entry o1, Map.Entry o2) {
                return o1.getValue() - o2.getValue();
            }
        });
        for (Map.Entry entry : list1) {
            System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
        }
    }
}

 

你可能感兴趣的:(后端技术)