使用Java8中的多个键对地图列表进行排序 [英] Sort list of maps using multiple keys in Java8

查看:108
本文介绍了使用Java8中的多个键对地图列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有地图列表,我想使用键对列表内的地图进行排序.到目前为止,我已经使用下面的Collections.sort方法实现了这一点.

I have list of maps and I want to sort the maps inside the list using the keys. As of now I am achieving this using the below Collections.sort method..

Collections.sort(listOfMaps, new Comparator<Map<String, String>>() {
        @Override
        public int compare(Map<String, String> o1, Map<String, String> o2) {
            //return o1.get("cm_order_x").compareTo(o2.get("cm_order_x"));
            String x1 = o1.get(Key1);
            String x2 = o2.get(Key1);
            String x3 = o1.get(Key2);
            String x4 = o2.get(Key2);
            int sComp = x1.compareTo(x2);
            int sComp1 = x3.compareTo(x4);
            if (sComp != 0) {
               return sComp;
            }
            else if(sComp1 != 0) {

                //return x3.compareTo(x4);
                return sComp1;
            }


                else
                {
                    String x5 = o1.get(Key3);
                    String x6 = o2.get(Key3);
                    return x5.compareTo(x6);
                }
             }

    });

在Java 8中还有其他更好的方法来对mapslist进行排序吗?

Is there any other better way to sort the list of maps in Java 8 ?

推荐答案

自Java8开始,Comparator接口提供了工厂方法和链接方法:

Since Java8, the Comparator interface offers factory methods and chaining methods:

Comparator<Map<String, String>> c
    = Comparator.comparing((Map<String, String> m) -> m.get(Key1))
                .thenComparing(m -> m.get(Key2))
                .thenComparing(m -> m.get(Key3))
                .thenComparing(m -> m.get(Key4));

listOfMaps.sort(c);

这篇关于使用Java8中的多个键对地图列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆