dart

find highest value in Map <Object?, Object?>


I want to resolve the highest value of a Map, with different field names. In this case highestValue should be "Luke"

String? highestValue;
   
Map<Object?, Object?>? points =
     {
       "Vader": 40,
       "Obi-Wan": 20,
       "Luke": 50,
     };
   
highestValue = ...

Solution

  • Your map is terribly typed so I am not sure what situations we need to take into account here. E.g. what should happen if the value are not an int? But I have made the following example of how you could do it:

    void main() {
      String? highestValue;
    
      Map<Object?, Object?>? points =
      {
        "Vader": 40,
        "Obi-Wan": 20,
        "Luke": 50,
      };
    
      highestValue = points.entries.reduce((a, b) {
        final aValue = a.value;
        final bValue = b.value;
    
        if (aValue is! int) {
          return b;
        }
    
        if (bValue is! int) {
          return a;
        }
    
        return aValue > bValue ? a : b;
      }).key as String?;
    
      print(highestValue); // Luke
    }
    

    But as you can see, a lot of the logic comes from the fact that your map contains Object? objects and not a more specific type like int.

    Extra solution added after request in comment

    If we want to have extract the second biggest, we are starting to get into the territory where it makes more sense to just generate a list and then order it.

    So we can do something like this where we do this based on the map:

    void main() {
      String? highestValue;
    
      Map<Object?, Object?>? points = {
        "Vader": 40,
        "Obi-Wan": 20,
        "Obi-Wan": 20,
        "Luke": 50,
      };
    
      final sortedEntries = points.entries.toList()
        ..sort((entry1, entry2) {
          final aValue = entry1.value;
          final bValue = entry2.value;
    
          if (aValue is! int) {
            return 1;
          }
    
          if (bValue is! int) {
            return -1;
          }
    
          return bValue.compareTo(aValue);
        });
    
      sortedEntries
          .forEach((entry) => print('Key: ${entry.key} | Value: ${entry.value}'));
      // Key: Luke | Value: 50
      // Key: Vader | Value: 40
      // Key: Obi-Wan | Value: 20
    
      String nameOfTheSecondLargest = sortedEntries[1].key as String;
      print(nameOfTheSecondLargest); // Vader
    }