Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Streaming over a Java list to populating a Map

Java 11 here. I have the following POJO:

@Data // Lombok; adds getters, setters, all-args constructor and equals and hashCode
public class Fliflam {
    private String merf;
    private String tarf;
    private Boolean isFlerf;
}

I have a method that validates a Flimflam and returns a List<String> of any errors encountered while validating the Flimflam. I can change this to return Optional<List<String>> if anyone thinks thats helpful for some reason, especially when dealing with the Stream API:

public List<String> validateFlimflam(Flimflam flimflam) {
    List<String> errors = new ArrayList<>();

    // ... validation code omitted for brevity
    // 'errors' list is populated with any errors; otherwise it returns empty

    return errors;
}

I want to stream (Stream API) through a List<Flimflam> and populate a Map<Flimflam,List<String>> errors map, where the key of the map is a Flimflam that failed validation, and its corresponding value is the list of validation error strings.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I can achieve this the "old fashioned" way like so:

List<Flimflam> flimflams = getSomehow();
Map<Flimflam,List<String>> errorsMap = new HashMap<>();
for (Flimflam ff : flimflams) {
    List<String> errors = validateFlimflam(ff);
    if (!errors.isEmpty() {
        errorsMap.put(ff, errors);
    }
}

How can I accomplish this via the Stream API?

>Solution :

Like this

Map<Flimflam,List<String>> errorsMap = flimflams.stream().collect(Collectors.toMap(f -> f, f-> f::validateFlimflam));

toMap takes 2 parameters (keyMapper,valueMapper)
In your case key mapper is object from stream itself, and value is calling validateFlimflam on that object

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading