2

Lets say I have data which has following structure.

//map1        //map2         //map3
Fruit-------->Apple--------->Green Apple------->4
                             Red Apple--------->5
                             Yellow Apple------>6
                             Total------------->15
              Cherry-------->Red Cherry-------->5
                             Green Cherry------>3
                             Total------------->8
Vegetable----->Capsicum----->Green Capsicum---->5
                             Red Capsicum------>7
                             Yellow Capsicum--->3
                             Total------------->15

In other words I have

Map<String, Map<String, Map<String, Long>>>

I want to sort the innermost map(map3) by values and the middle map(map2) by the value of entry "total" in map3.

I know that typically we can sort the map by value as follows.

import java.util.*;

public class MapUtil
{
 public static <K, V extends Comparable<? super V>> Map<K, V> 
    sortByValue( Map<K, V> map )
 {
    List<Map.Entry<K, V>> list =
        new LinkedList<Map.Entry<K, V>>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>()
    {
        public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            return (o1.getValue()).compareTo( o2.getValue() );
        }
    } );

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
  }
} 

But here the value is a long and not map. I am working on this problem and I think this can be a good way to learn more about maps. Any idea or suggestion about how this can be achieved?

Pratik Patel
  • 1,305
  • 1
  • 17
  • 44

0 Answers0