Search code examples
javafunctionjava-streamcollectors

How to create a map with an attribute as a key and a maximum value as a value


In college we are working with CSV files and streams. Right now I am doing some homework but I've been stuck in this exercise for some days now.

I have a CSV file with some data about accidents (like the accident severity, the number of victims and so on) and I have a function that reads that data and converts it to a list of Accident objects (which has a property for each type of data the CSV has):

public class Accident {
    private Severity severity;
    private Integer victims;
    
    public Accident(Severity severity, Integer victims) {
        this.severity = severity;
        this.victims = victims;
    }
}

I have saved that list in an object and I can call the list with getAccidents():

private List<Accident> accidents;

public AccidentArchive(List<Accident> accidents) {
    this.accidents = accidents;
}

public Map<Severity, Integer> getMaxVictimsPerSeverity() {
    //Not working correctly
    return getAccidents().stream().collect(Collectors.toMap(Accident::getSeverity, Accident::getVictims, Integer::max));
}

Right now, I have to make a function that creates a map with an attribute as a key and a maximum value as a value. I have thought that the map keys could be the severity (which is an enum with values SLIGHT, SERIOUS and FATAL) and the values could be the highest number of victims of every accident with that same severity.

For example, the map output could be: SLIGHT=1, SERIOUS=3, FATAL=5.

I have tried using the Collections, Collectors and Comparator libraries but I can't find any way to divide all the Accidents in each severity value, get the maximum number of victims for each and then save both values in a Map<Severity, Integer>.

The function right now starts this way:

public Map<Severity, Integer> getMaxVictimsPerSeverity() {
    return getAccidents().stream().collect(Collectors.toMap(Accident::getSeverity, ...))

I have tried a lot of things but I can't find any way to make it return what I want. How can I do this?


Solution

  • Provide a value extractor to get the victims of each accident, and a reducer to keep the highest number of victims.

    return getAccidents().stream()
        .collect(Collectors.toMap(Accident::getSeverity, Accident::getVictims, Integer::max));