1

I have a HashMap with a String and an array of Integer and I want to sort the map by the first value of the array.

For example, in the entries:

{"Name1"=[2,4],
 "Name2"=[1,5],
 "Name3"=[3]}

the order should be:

{"Name2"=[1,5],
 "Name1"=[2,4],
 "Name3"=[3]}
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
Froddy
  • 33
  • 3

1 Answers1

1

I want to sort the map by the first value of the array

We can use a custom comparator in the stream extracted from the Map.entrySet() which takes into consideration the first element of the array from the value of the Map when doing the comparison:

 Map<String, Integer[]> map = new HashMap<>();
 map.put("Name1", new Integer[]{2,5});
 map.put("Name2", new Integer[]{1,4});
 map.put("Name3", new Integer[]{3});


 Map<String, Integer[]> sorted = map
                             .entrySet().stream()
                             .sorted(Comparator.comparing(ent -> ent.getValue()[0]))
                             .collect(Collectors.toMap(Map.Entry::getKey, 
                                                      Map.Entry::getValue,
                                                      (a, b) -> b,                                                        
                                                     LinkedHashMap::new));

 sorted.forEach((k,v) -> System.out.println("{ " + k + " " + Arrays.toString(v) + " }"));

Output:

{ Name2 [1, 4] }
{ Name1 [2, 5] }
{ Name3 [3] }
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44