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

Time:06-23

I try 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 = ...

thanks

CodePudding user response:

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
}

CodePudding user response:

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

String highest = points.keys.first;
int max = points.values.first;

points.forEach((key, value) {
  if(max < value){
    max=value;
    highest = key;
  }
});

You can do something like this. More easy to understand.

CodePudding user response:

Simplest way to do this :

import:

import 'dart:math';

then

Map<Object?, Object?> points = {
          "Vader": 40,
          "Obi-Wan": 20,
          "Luke": 50,
        };
var highestValue = (points.values.toList().map((e) => e as int).reduce(max));
print(highestValue);
  •  Tags:  
  • dart
  • Related