From a Java Stream of Map group them by keys and find the maxium value not working as expected

Jay :

From an input Stream<Map<String,Float> I am trying to find the unique analytes and which has the maxium value. I tried the below but not getting the expected result. I am making some mistake in collecting the value.

Sample Input Data: List<Map<String,Float>

{HNO3=2.005}
{HNO3=2.009}
{HCl=10.2}
{F-=0.0, HNO3=50.0}

Actual result   : {HCl=Optional[HCl=10.2], F-=Optional[F-=0.0], HNO3=Optional[HNO3=50.0]}
Expected result : {HCl=10.2, F-=0.0, HNO3=50.0}

Java code I tried:-

finalResponse.getChosenStartingMaterials()
    .stream()
    .map(Analyte::getMatrixUtilisationMap)  // Stream<Map<String,Float>>
    .flatMap(it -> it.entrySet().stream())   
    .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.maxBy((m1, m2) -> m1.getValue().compareTo(m2.getValue()))))
Eran :

Collectors.maxBy() produces an Optional, since if maxBy is applied on an empty Stream, it has to return an empty Optional.

You can use Collectors.toMap instead of Collectors.groupingBy to avoid the Optionals:

finalResponse.getChosenStartingMaterials()
    .stream()
    .map(Analyte::getMatrixUtilisationMap)  // Stream<Map<String,Float>>
    .flatMap(it -> it.entrySet().stream())   
    .collect(Collectors.toMap(Map.Entry::getKey,
                              Map.Entry::getValue,
                              (v1, v2) -> v1.compareTo(v2) >= 0 ? v1 : v2));

or

finalResponse.getChosenStartingMaterials()
    .stream()
    .map(Analyte::getMatrixUtilisationMap)  // Stream<Map<String,Float>>
    .flatMap(it -> it.entrySet().stream())   
    .collect(Collectors.toMap(Map.Entry::getKey,
                              Map.Entry::getValue,
                              Float::max));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=4301&siteId=1