Collectors.toMap gives compilation error (String,List<String) is not applicable for the arguments

mmathank :
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamExample {

    public static void main(String[] args) {

        Student student = new Student();
        StudentDB studentDb = new StudentDB();

        System.out.println("All Elements from the List \n");
        studentDb.getStudentList().forEach(System.out::println);

        Map<String, List<String>> studentMap = studentDb.getStudentList().stream()
                .collect(Collectors.toMap(student.getName(), student.getActivities()));

    }
}
azro :

A thing, you're using student.getName(), which just calls a method on an object, so you'll get its name and its activites, you'll get values, no generic method to end the Stream


The Collectors.toMap expects you to pass functions (Function<Student,String> for key, Function<Student,List<String>> for value), that from a Student will give something else

  • You can express it with a lambda : s -> s.getName()

    Map<String, List<String>> studentMap = studentDb.getStudentList().stream()
                   .collect(Collectors.toMap(s -> s.getName(), s -> s.getActivities()));
    
  • Or method reference Student::getName, you use the method itself, not applied on a specific object

    Map<String, List<String>> studentMap = studentDb.getStudentList().stream()
                   .collect(Collectors.toMap(Student::getName, Student::getActivities));
    

Guess you like

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