0

Is there a way to do this? I was thinking it could be done with streams but I'm not super experienced with them and would like some help regarding that.

For example: If the hashmap is currently like:

"A" : 5

"B" : 2

"C" : 4

You then return ["A", "C", "B"].

Jon
  • 481
  • 1
  • 6
  • 12

5 Answers5

1
 Map<String, Integer> sortedMap = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
  • I think you mean `comparingByValue`. Also, the OP just requested the keys, you don't need to return a map. – Louis Wasserman May 22 '21 at 17:06
  • Yes, what would the altered stream look like? Also, to strengthen my understanding of streams, could you perhaps break down what this code does? I understand you get the `entrySet`, turn it into a stream, sort based on a `Comparator` provided by `comparingByKey`, then collect it back, but I don't quite understand what's within the `collect` method, or more specifically, the `toMap` method, both with the double colon and the lambda expression. – Jon May 22 '21 at 17:54
  • considering the question, I think it is clear that the OP wants to retrieve all keys in a sorted way. Not the whole map sorted – Panagiotis Bougioukos May 22 '21 at 19:35
1

You can use TreeMap it will give you ordered by keys

List<Character> sortedKey() {
    Map<Character, Integer> map = new TreeMap<>();
    List<Character> list = new ArrayList<>();
    for(Map.Entry entry: map.entrySet()) {
        list.add((Character)entry.getKey());
    }
    return list;
}
0

Using collections.sort approach:

  1. convert HashMap to List
  2. sort list using custom comparator
  3. then create list of key(sorted order based on their values)

code:

// function to sort hashmap by values
public static List sortByValue(HashMap < String, Integer > hm) {
  // Create a list from elements of HashMap
  List < Map.Entry < String, Integer > > list =
    new LinkedList < Map.Entry < String, Integer > > (hm.entrySet());

  // Sort the list
  Collections.sort(list, new Comparator < Map.Entry < String, Integer > > () {
    public int compare(Map.Entry < String, Integer > o1,
      Map.Entry < String, Integer > o2) {
      return (o2.getValue()).compareTo(o1.getValue());
    }
  });

  // put data from sorted list to hashmap
  List < String > temp = new ArrayList < String > ();
  for (Map.Entry < String, Integer > aa: list) {
    temp.add(aa.getKey());
  }
  return temp;
}
Md Kawser Habib
  • 1,966
  • 2
  • 10
  • 25
0

Given

Map<String,Integer> map = Map.of("A",5,"B",2,"C",4);

This is relatively simple.

  • stream the entrySet and sort in reversed order using the Entry comparator for values.
  • then get the key and collect to a list. If you return a set, they may not be in sorted order. Nor can you access elements in a set as easily as a List, even if a LinkedHashSet is used to preserve order.
List<String> keys = map.entrySet().stream()
.sorted(Entry.<String,Integer>comparingByValue()
        .reversed()).map(Entry::getKey)
        .toList();  // java 16+ -- prior to Java 16 use .collect(Collectors.toList())

System.out.println(list);

prints

[A, C, B]
WJS
  • 36,363
  • 4
  • 24
  • 39
0

Create new List of Map.Entries and sort List using method Map.Entry.comparingByValue witch returns a comparator that compares Map.Entry in natural order on value and then turns it in reverse order:

List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
System.out.println(list);
Sergey Afinogenov
  • 2,137
  • 4
  • 13