Reputation: 97
I am in need of help to create a hashmap.
public class Driver {
private String id;
private String name;
private List<Student> students;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
public class Student {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
There will be a List of Driver objects. Every Driver has List of Student objects. Could someone help me how to create this Map using streams: <Student.id, Driver.id>
Thanks!
Upvotes: 0
Views: 84
Reputation: 393781
You can use flatMap
to build a Stream
of all the (Student ID, Driver ID) pairs and then collect them into a Map
:
List<Driver> drivers = new ArrayList<> ();
Map<String,String>
studentDrivers =
drivers.stream ()
.flatMap (drv -> drv.getStudents ()
.stream ()
.map (st -> new SimpleEntry<String,String> (st.getId (), drv.getId ())))
.collect (Collectors.toMap (Map.Entry::getKey,
Map.Entry::getValue));
Upvotes: 2