0

I have a nested map Map<String, Map<String, Integer> for example

("Samsung", ("Note", 30))

("Samsung", ("Galaxy", 20))

("Apple", ("Iphone", 40))

I need to sort the map by inner key alphabetically in descending (in this example case - the model name)

and if two names are equal then I have to sort the inner values in ascending (in this case - the price).

My sorting by far is like this:

map.entrySet().stream.forEach(entry -> entry.getValue().entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getKey, Comparator.reverseOrder()))

And I know I have to add .thenComparing(), but I don't know how to proceed next.

1 Answers1

0

You write a CustomComparator as Follows:

import java.util.*;

public int compare(Object obj1  , Object obj2){

        Map<String, Map<String, Integer> > map1 = (Map<String, Map<String, Integer>) obj1;
        Map<String, Map<String, Integer> > map2 = (Map<String, Map<String, Integer>) obj2;
        Map.Entry e1 = (Map.Entry)map1.entrySet();
        Map.Entry e2 = (Map.Entry)map2.entrySet();
        String brand1 = (String)e1.getKey();
        String brand2 = (String)e2.getKey();
        Map.Entry e3 = (Map.Entry)e1.getValue();
        Map.Entry e4 = (Map.Entry)e3.getValue();
        Integer price1 =(Integer) e3.getValue();
        Integer price2 =(Integer) e4.getValue();

        if(brand2.compareTo(brand1) != 0){
            return brand2.compareTo(brand1);
        }else{
            price1.compareTo(price2);
        }
      }
    }

This Compactor will sort data in descending order of brand name first And if two brand having same name then for that it will sort in ascending order of price .

You have to add your data in TreeMap as follows

Set data = new TreeSet(new CustomComparator()); //Add your data here in data object

Ajinkya
  • 325
  • 3
  • 12