I am trying to convert a List of Student objects into a map in which key is the integer(i.e. rollno field of Student object) and Value is the Student Object itself.
The following is the code that i have written:
package fibonacci;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MApfor {
public static void main(String[] args) {
List<Student> maplist=new ArrayList<>();
maplist.add(new Student(1, "pavan"));
maplist.add(new Student(2, "Dhoni"));
maplist.add(new Student(3, "kohli"));
maplist.forEach(System.out::println);
Map<Integer,Student> IS=new HashMap<>();
IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo,a);
}
}
Whenever i try to write the last line, i.e.
IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo,a);
i am unable to retrieve the rollNo field, eclipse is not showing the suggestions i.e. whenever i type a.get to assign the rollNo to key,i am not able to do so.
Please suggest the issue that i am facing.
package fibonacci;
public class Student {
public int rollNo;
public String name;
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(int rollNo, String name) {
super();
this.rollNo = rollNo;
this.name = name;
}
@Override
public String toString() {
return " [rollNo=" + rollNo + ", name=" + name + "]";
}
}
IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo,a -> a);