0

I hava a structure that is a Map that contains pairs: String=>Map. Is there a way to sort this Map (root) by multiple values? Example to be clear:

Input:

"A" => {name: "John", age: "47"}
"B" => {name: "Sam", age: "60"}
"C" => {name: "Josh", age: "30"}
"D" => {name: "Tom", age: "15"}
"E" => {name: "Josh", age: "31"}

Sorted:

//group 1
"A" => {name: "John", age: "47"} 
//group2
"C" => {name: "Josh", age: "30"} 
"E" => {name: "Josh", age: "31"} 
//group3
"B" => {name: "Sam", age: "60"} 
//group4
"D" => {name: "Tom", age: "15"}

Output map is sorted first by name, then (within sorted groups) by age. I am able to sort by single map value entry, but I can't find an easy(-ish) way to sort by multiple entries (in given order). I can try to split this structure after every sort, apply next level sort and join everything at the end, but I am looking for more fancy solution (if there is one).

Any ideas?

Kamil Kłys
  • 1,907
  • 3
  • 18
  • 30

1 Answers1

2

Java provides a TreeMap which will allow you to specify a comparator in which it will sort your input.

To use the TreeMap in a traditional way, you will need to do something like so:

private class Person implements Comparable<Person>{
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }

    @Override
    public int compareTo(Person t) {
        if(!this.getName().equals(t.getName()))
            return this.getName().compareTo(t.getName());

        return Integer.compare(this.getAge(), t.getAge());
    }
}

private class CustomComparator implements Comparator<Person> {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.compareTo(p2);
    }
}

public NewClass()
{
    SortedMap<Person, String> map = new TreeMap<Person, String>(new CustomComparator());

}

So basically you would need to swap the key and value pairs. If this is not what you are after, then you can take a look at this previous SO questions for more answers.

Community
  • 1
  • 1
npinti
  • 51,780
  • 5
  • 72
  • 96
  • Does this make the `Map` implementation specific? – Reut Sharabani Aug 26 '15 at 07:31
  • 2
    @ReutSharabani: If you go for `TreeMap` yes, since you will be using a concrete class. If you want to go for interfaces, then you can write your code against a [`SortedMap`](https://docs.oracle.com/javase/8/docs/api/java/util/SortedMap.html). – npinti Aug 26 '15 at 07:34
  • I wanted to avoid using separate class, but I guess that's clean and simple. Thanks! – Kamil Kłys Aug 26 '15 at 20:25