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

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

Posted by: admin February 25, 2020 Leave a comment

Questions:

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()))))
How to&Answers:

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));