sparkey
sparkey

Reputation: 168

Sort list of maps using multiple keys in Java8

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);
                }
             }

    });

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

Upvotes: 0

Views: 3276

Answers (3)

Holger
Holger

Reputation: 298153

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);

Upvotes: 4

Shadov
Shadov

Reputation: 5592

There is no possibility of this, since you are sorting depending of something only you know.

What I mean is you are first comparing by Key1, then Key2 etc. Keys are not numbered in a map, here Key1 doesn't mean first key, but some key that you want compared first. There is no way to tell that to java, this behaviour is too specific.

You can come up with something for a generic solution (like for a map with more keys, so you don't have to list them all like that), but you are not gonna avoid the main problem of this implementation.

Upvotes: 0

broxhouse
broxhouse

Reputation: 17

I believe you can accomplish this task by using code like this:

listOfMaps.sort(Comparator.comparing(
                m -> m.get("yourKey"), 
                Comparator.nullsLast(Comparator.naturalOrder()))
           )

See: How can I sort a list of maps using Java 8?

Upvotes: 0

Related Questions