0

I have the following imperative programming code snippet here:

    Map<String, Integer> nameCounts = new ConcurrentHashMap<>();
    String mostCommon = null;
    int mostCommonCount = -1;
    for (Map.Entry<String, Integer> entry : nameCounts.entrySet()) {
        if (mostCommon == null || entry.getValue() > mostCommonCount) {
            mostCommon = entry.getKey();
            mostCommonCount = entry.getValue();
        }
    }

When executed with certain data, nameCounts should contain results such as:

nameCounts = {HashMap@795}  size = 6
 0 = {HashMap$Node@805} "William" -> "232818"
 1 = {HashMap$Node@806} "Dennis" -> "233249"
 2 = {HashMap$Node@807} "Maynard" -> "233205"
 3 = {HashMap$Node@808} "Vincent" -> "233288"
 4 = {HashMap$Node@809} "John" -> "234109"
 5 = {HashMap$Node@810} "Donald" -> "233331"

What is the functional approach by using Java 8's Streams I could use, to get the String with the highest value? (in this case, it would be "John").

Thanks in advance!

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
noloman
  • 11,411
  • 20
  • 82
  • 129
  • Where's your ``ConcurrentHashMap`` ? – Schidu Luca Sep 06 '17 at 14:36
  • there it is @SchiduLuca – noloman Sep 06 '17 at 14:49
  • Specific for a `ConcurrentHashMap`, you can use `Map.Entry maxEntry = nameCounts.reduceEntries(8, BinaryOperator.maxBy(Map.Entry.comparingByValue()));` (if the variable has been declared as `ConcurrentHashMap` rather than just `Map`). The first parameter (the eight in my example) specifies the desired number of threads. Otherwise, for general `Map` solutions, follow the link… – Holger Sep 06 '17 at 17:17

0 Answers0