I have a List and a Map as below:
public class student {
private String name;
private String age;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
student(String id,String name,String age)
{
}
}
List<student> stulist = Arrays.asList(new student("1", "vishwa",null),
new student("3", "Ravi",null),
new student("2", "Ram",null));
Map<String,String> newmap = new HashMap() {
{
put("1","20");
put("2","30");
}
};
I am comparing like this: If id in map matches the id in list then add
age from Map to age of List.
I have tried this so far , but i am not able to get it.
newmap.entrySet().stream().filter(entry->entry.getKey().equals(student::getId)).collect(..collect here to list..);
Here is solution, assuming I got the question right:
import java.util.*;
import java.util.stream.*;
public class Answer {
public static void main(String[] args) {
List<Student> studentsWithoutAge = Arrays.asList(
new Student("1", "Vishwa", null),
new Student("3", "Ravi", null),
new Student("2", "Ram", null)
);
Map<String,String> ageById = new HashMap() {{
put("1","20");
put("2","30");
}};
List<Student> studentsWithAge = addAge(studentsWithoutAge, ageById);
System.out.println("Students without age: " + studentsWithoutAge);
System.out.println("Students with age: " + studentsWithAge);
}
static List<Student> addAge(List<Student> students, Map<String,String> ageById) {
return students.stream()
.map(student -> {
String age = ageById.getOrDefault(student.getId(), null);
return new Student(student.getId(), student.getName(), age);
})
.collect(Collectors.toList());
}
}
class Student {
private String name;
private String age;
private String id;
Student(String id,String name,String age){
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return String.format("Student: id = %s, name = %s, age = %s", this.id, this.name, this.age);
}
}
stulist = stulist.stream().map(instance -> {
student studentInstance = instance;
studentInstance.setAge(newMap.getOrDefault(studentInstance.getId(),"<default age>"));
return studentInstance;
}).collect(Collectors.toList()); ;
ps: Use proper naming conventions. Change the class name student to Student.
Implement Student class as @Zgurskyi comment, and then use this on main:
stulist.forEach(stu -> {
stu.setAge(newmap.getOrDefault(stu.getId(), null));
});
Use Collectors.toList()
// Accumulate names into a List
List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());