1

My goal is to have is given a map of to return an ascending array/list of sorted key values. For example:

Input: the Map containing the following key/value entries separated by a space:

"Apple" 10
"Orange" 8
"Kiwi" 15

Output:

{Orange;Apple;Kiwi}

The only other approach I could think of was creating a Map<Integer,Set<String>> and then sorting by the key which is fairly convoluted. I got this approach to work but it seems rather inefficient in terms of code and logic. Thanks so much!

user3750474
  • 249
  • 5
  • 18

3 Answers3

2

One technique is to push the Map into a List, and then use a Comparator to sort the values before putting that back into a Map.

e.g., something like:

List<Map.Entry<String, Integer>> list = 
            new LinkedList<Map.Entry<String, Integer>>(mapYouPassedIn.entrySet());

Then you can use Collections.sort() plus a Comparator to do the grunt work over this list.

1

In java 8 there is a very simple approach to this using streams:

map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

For example:

public class Test {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();
        map.put("A", 2);
        map.put("B", 3);
        map.put("C", 1);
        System.out.println(map.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey)
            .collect(Collectors.toList()));
    }
}

prints [C, A, B]

sprinter
  • 27,148
  • 6
  • 47
  • 78
  • this doesn't compile for some reason... – user3750474 Jan 27 '15 at 05:13
  • what error do you get? – sprinter Jan 27 '15 at 05:18
  • it is java 8. what is your compiler version? – Bruce Jan 27 '15 at 05:29
  • 1
    @Exbury Java 8 has been out for quite a while now. Do we really need to keep qualifying answers with it? – sprinter Jan 27 '15 at 05:43
  • That's odd. I do have Java 8. javac 1.8.0_31 to be exact – user3750474 Jan 27 '15 at 06:22
  • I get the Map.Entry cannot be resolved to a variable – user3750474 Jan 27 '15 at 06:23
  • @user3750474 I edited the code a bit: I was using a method reference instead of a direct method call. Can you try it again using `Map.Entry.comparingByValue()`? I've tried this myself and it works for me. – sprinter Jan 27 '15 at 06:24
  • Error: The method sorted(Comparator super Map.Entry>) in the type Stream> is not applicable for the arguments (Comparator>>>) Map.Entry cannot be resolved to a variable Syntax error on tokens, delete these tokens – user3750474 Jan 27 '15 at 06:27
  • That's surprising. I'm using a map to integer rather than double but I can't see why that should matter. I'll post my test program in the answer - cut and paste that to a new project and see if you get the same error. – sprinter Jan 27 '15 at 06:32
  • How can I ? 1. Print Value with key 2) Can we sort the values in descending order? – Rohan Jul 22 '21 at 15:50
  • Not sure if its sorting for printing or not. After your SOP, when I print again, it shows original map. Does it require to be in new map? if yes how? System.out.println(map.toString()); [C, A, B] {A=2, B=3, C=1} – Rohan Jul 22 '21 at 16:11
0

You can get entrySet from hashMap and sort Map.entry list. eg:

List<Map.Entry<Integer, Integer>> list = new LinkedList<Map.Entry
<Integer,    Integer>>( map.entrySet() );
    Comparator<Map.Entry<Integer, Integer>> comp = 
new   Comparator<Map.Entry<Integer, Integer>>()
    {

        @Override
        public int compare( Entry<Integer, Integer> o1, Entry<Integer, Integer> o2 )
        {
            return ( o1.getValue() ).compareTo( o2.getValue() );
        }
    };

    Comparator<Map.Entry<Integer, Integer>> cmp1 = Collections.reverseOrder( comp );
    Collections.sort( list, cmp1 );
Vishwas
  • 43
  • 5