Reputation: 249
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 + "]";
}
}
Upvotes: 1
Views: 2803
Reputation: 27018
It should be like this
maplist.stream().collect(Collectors.toMap(a -> a.rollNo, Function.identity()));
or even better is to use getters with method references.
maplist.stream().collect(Collectors.toMap(Student::getRollNo, Function.identity()));
a -> a.getRollNo
this is incorrect. You should use the public field or the getter. You are using neither correctly.
when you say a.getRollNo
, this means there should be a public field by name getRollNo in your class, which is not true. Your field is called rollNo.
Then if you want to access the getter method of rollNo, then it should be like a.getRollNo(). (you were missing ()
in the end).
But you can use method references like this Student::getRollNo
also
So it should be either one of these
a -> a.rollNo
a -> a.getRollNo()
Student::getRollNo
You can replace Function.identity()
with a -> a
as well.
Upvotes: 5
Reputation: 54148
a.getRollNo
does not exists, the proper getter is a.getRollNo()
(or a.rollNo
directly, but you'd better set your members as private
)a -> a
function, map the object to itself :IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo(), a -> a));
// or
IS = maplist.stream().collect(Collectors.toMap(a -> a.getRollNo(), Function.identity());
Using method reference
IS = maplist.stream().collect(Collectors.toMap(Student::getRollNo, Function.identity()));
Upvotes: 1