The method max(Comparator<? super List<Integer>>) in the type Stream<List<Integer>> is not applicable for the arguments (Comparator<Integer>)

Murali krishna Konduru :

I am trying to fetch the student name based on his maximum marks using java8 streams API.

import static java.util.Arrays.asList;
public class Main {

    public static void main(String args[]) {
        new StudentReport(asList(
                new StudentData("Rohit", asList(100, 81, 82, 83)),
                new StudentData("Ram", asList(84, 85, 86, 87))));
    }
}   

import java.util.List;
public class StudentData {

    private String name;
    private List<Integer> marks; 

    StudentData(String name, List<Integer> marks) {
        this.name = name;
        this.marks = marks;
    }    
    public String getName() {
        return name;
    }    
    public void setName(String name) {
        this.name = name;
    }    
    public List<Integer> getMarks() {
        return marks;
    }    
    public void setMarks(List<Integer> marks) {
        this.marks = marks;
    }
}

import java.util.Comparator;
import java.util.List;
import java.util.stream.Stream;

public class StudentReport {

    public StudentReport(List<StudentData> studentData)
    {
        printStudentNameWithMaxMarks(studentData);  
    }

    private void printStudentNameWithMaxMarks(List<StudentData> studentData) {
// I am getting erro here.
        studentData.stream().map(student -> student.getMarks())
        .max(Comparator.comparing(Integer::intValue)).get();
    }

}

I would like to return the "Rohit" in output because he scores max 100 marks. whether it is possible to achieve in a single stream operation, compare all the marks and return

new StudentData("Rohit", asList(100, 81, 82, 83)),
new StudentData("Ram", asList(84, 85, 86, 87))));

Thanks in Advance and appreciating your help.

Joakim Danielson :

For your current attempt you need to first get the max value for each student before comparing students max values to each other

studentData.stream().map(student -> Collections.max(student.getMarks()))
        .max(Comparator.comparing(Integer::intValue)).get();

The problem with the above code is that it returns the highest mark and not the student so so it needs to be rewritten

studentData.stream().sorted((s1, s2) -> Collections.max(s1.getMarks()).compareTo(Collections.max(s2.getMarks())))
    .findFirst().get();

The code above could be made easier to read if StudentData can give us the highest mark

public Integer highestMark() {
    return Collections.max(this.getMarks());
}


studentData.stream().sorted((s1, s2) -> s1.highestMark().compareTo(s2.highestMark())).findFirst().get();

Guess you like

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