0

I have the following scenario where I try to order map values by the key. After The key order the first value has to be value which was order by.

import java.util.Comparator;
import java.util.Map;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;

public class MyEnumKeySortTest {


    enum Key{
        key1, key2
    }

    enum Door{
        door1, door2 
    }


     public static void main(String[] args) {
        Map<Key, Door> test = ImmutableMap.<Key, Door> of(Key.key1, Door.door1, Key.key2, Door.door2);

        printValues(test);
        Comparator<Key> comparator =  Ordering.explicit(Key.key1);
        /*
         *  should print
         *  
         *  door1
         *  door2
         */

        test = Maps.newTreeMap(comparator);
        printValues(test);

        Comparator<Key> comparator2 =  Ordering.explicit(Key.key2);
        /*
         *  should print
         *  
         *  door2
         *  door1
         */

        test = Maps.newTreeMap(comparator2);
        printValues(test);

     }


    private static void printValues(Map<Key, Door> test) {
        System.out.println("==========================================================");
        for(Door r : test.values()){
            System.out.println(r.name());
        }
    }

}
Njax3SmmM2x2a0Zf7Hpd
  • 1,354
  • 4
  • 22
  • 44
  • 2
    It's really confusing what you mean. What is `Ordering.explicit` being used for? Are you actually trying to sort by the key, or the value? Why are you not using `ImmutableSortedMap` from the beginning, if you are sorting by the key? – Louis Wasserman Mar 30 '15 at 19:51
  • I wanted that key-value to be the first value out. from the existing map. – Njax3SmmM2x2a0Zf7Hpd Mar 30 '15 at 19:53
  • _Which_ key-value? (`Ordering.explicit` has to take all the values in the order you want -- so `Ordering.explicit(key1, key2)` to put key1 before key2.) – Louis Wasserman Mar 30 '15 at 19:55
  • I don't think Guava is of great help for this problem. Possible duplicate of http://stackoverflow.com/questions/922528/how-to-sort-map-values-by-key-in-java – Fritz Duchardt Mar 31 '15 at 12:34

1 Answers1

0

Put Map.Entry into a list, and sort it using a comparator that sorts the value -

List list = new ArrayList(map.entrySet());
Collections.sort(list, new Comparator() {

  @Override
  public int compare(Entry e1, Entry e2) {
    return e1.getKey().compareTo(e2.getKey());
  }

});

Or some implementation of SortedMap like - TreeMap can be used. In this case all keys may have to implement the Comparable

Razib
  • 10,965
  • 11
  • 53
  • 80