Search code examples
javahashmapjava-stream

Java 8 Stream - Find greatest amount for Map<String, List<Object>>


How is it possible to find max sold inside a Map<String,List<Account>>

  class Account {
     String hashId;
     String address;
     BigDecimal sold;
  }

I saw this discussion but I cannot modify it for my case, I have to search through all the Lists to get the greatest sold value.

Java 8 stream - Find max count values for Map<String, List<Object>>


Solution

  • If you just want the max sold and nothing else you could do the following:

    Here I assume your Map is named "map" and that sold has a getter named getSold.

    This will return an Optional with the max value.

    map.values()
       .stream()
       .flatMap(listOfAccounts -> listOfAccounts.stream().map(Account::getSold))
       .max(BigDecimal::compareTo);