2

I have below hashmap like below:

  Map<String, Integer> map = new HashMap<String, Integer>();

  map.put("a", 4);
  map.put("b", 9);
  map.put("c", 1);

I want to sort the hashmap based by their value, it should give output like :

[1, 4, 9]

Is this possible using Comparator?

UPDATE: Link provided does not provide the solution, I tried the solution, created hashmap cannot be traversed by key.

Ankush soni
  • 1,439
  • 1
  • 15
  • 30
Vini Soni
  • 51
  • 8
  • 5
    possible duplicate of [How to sort a Map on the values in Java?](http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java) – SMA Aug 09 '15 at 12:30
  • HashMaps doesn't have order. You will need to store these values somewhere else. – Pshemo Aug 09 '15 at 12:30
  • @Pshemo It is big hashmap, is it fine to store somewhere else and then sort by value? – Vini Soni Aug 09 '15 at 12:32
  • @ViniSoni check the link provided by SMA, I think you will get solution there, if not update here – Nitesh Virani Aug 09 '15 at 12:37
  • 1
    As I said, HashMaps are unordered structures so you can't enforce any order on them. You need new structure which will store this values and order it later. – Pshemo Aug 09 '15 at 12:38
  • @SMA It is worth mentioning that top answer in that duplicate is terrible, and OP should not use it. There are better alternatives in other answers. – Pshemo Aug 09 '15 at 12:39
  • 1
    @SMA I tried the solution provided in duplicate link but created hashmap cannot be traversed by key. – Vini Soni Aug 09 '15 at 12:45
  • @ViniSoni Paste your modified code. – SMA Aug 09 '15 at 12:48
  • Are you sure you want to use `HashMap`? If you want it to be sorted by value, why do you need un-sorted access by key? – Antonio Aug 09 '15 at 12:48

2 Answers2

3

A Java 8 solution that is collecting the stream in a Map:

   Map<String, Integer> map = new HashMap<>();

    map.put("a", 4);
    map.put("b", 9);
    map.put("c", 1);

    Map<String, Integer> orderedByValueMap =
            map.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry::getValue))
                .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,
                        (o1, o2) -> o1, LinkedHashMap::new));

    System.out.println(orderedByValueMap);

Output: {c=1, a=4, b=9}

dimitrisli
  • 20,895
  • 12
  • 59
  • 63
0
 Map<String, Integer> map = new HashMap<String, Integer>();
      map.put("a", 4);
      map.put("b", 9);
      map.put("c", 1);
      List<Integer> l = new ArrayList<Integer>(map.values());
      l.sort(null);
      System.out.println(l);

This code gives output as you needed.

pramod kumar
  • 275
  • 2
  • 12