Skip to content

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

So, 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) 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):

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 does what the title says. I have thought that the map keys could be the severity (which is an enumerate 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> map. The function right now starts this way: public Map<Severity, Integer> getMaxVictimsPerSeverity() { return getAccidents().stream().collect(Collectors.toMap(Accident::getSeverity, ...)) and then I have tried a lot of things but I can’t find any way to make it return what I want. I am still a newby and I don’t understand a lot of things yet so ask if I have forgotten anything.



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));
User contributions licensed under: CC BY-SA
6 People found this is helpful