I'm trying to get the same thing accomplished by using mapping() instead. The following is the complete code. I'm getting an error and I've spent enough time on it and still couldn't figure out what the error message is saying. Would you mind sharing with me what's that I'm not understanding here? The error came from:
Code: Select all
Map<Grade, List<Student>> grouping = ls.stream().collect(Collectors.groupingBy(x -> x.getGrade(), Collectors.mapping(x -> x.getName(), Collectors.toList())));
https://docs.oracle.com/javase/8/docs/a ... Collector-
Thanks.
Error message
***************
Schmichaels-MacBook-Pro:Java_Professional_Programs schmichael$ javac Student.java
Student.java:45: error: incompatible types: inference variable T#1 has incompatible bounds
Map<Grade, List<Student>> grouping = ls.stream().collect(Collectors.groupingBy(x -> x.getGrade(), Collectors.mapping(x -> x.getName(), Collectors.toList())));
^
equality constraints: Student
lower bounds: String,U
where T#1,U,T#2,A,R are type-variables:
T#1 extends Object declared in method <T#1>toList()
U extends Object declared in method <T#2,U,A,R>mapping(Function<? super T#2,? extends U>,Collector<? super U,A,R>)
T#2 extends Object declared in method <T#2,U,A,R>mapping(Function<? super T#2,? extends U>,Collector<? super U,A,R>)
A extends Object declared in method <T#2,U,A,R>mapping(Function<? super T#2,? extends U>,Collector<? super U,A,R>)
R extends Object declared in method <T#2,U,A,R>mapping(Function<? super T#2,? extends U>,Collector<? super U,A,R>)
1 error
My code
********
Code: Select all
import java.util.*;
import java.util.stream.*;
public class Student{
public static enum Grade{A, B, C, D, F}
private String name;
private Grade grade;
public Student(String name, Grade grade){
this.name = name;
this.grade = grade;
}
public String toString(){
return name + ":" + grade;
}
public String getName(){
return name;
}
public Grade getGrade(){
return grade;
}
public static void main(String... args){
List<Student> ls = Arrays.asList(new Student("S1", Grade.A), new Student("S2", Grade.A), new Student("S3", Grade.C));
Map<Grade, List<Student>> grouping = ls.stream().collect(Collectors.groupingBy(x -> x.getGrade(), Collectors.mapping(x -> x.getName(), Collectors.toList())));
System.out.println(grouping);
}
}