I using java 8 and i have two object look like :
Person class :
public class Person {
private String id;
private String name;
public Person() {
}
public Person(String id, String name) {
this.id = id;
this.name = 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;
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
Person1 Class :
public class Person1 {
private String id;
private String name;
public Person1() {
}
public Person1(String id, String name) {
this.id = id;
this.name = 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;
}
@Override
public String toString() {
return "Person1{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
I have two list look like :
List<Person> persons= Arrays.asList(new Person("1","A"),new Person("2","B"));
List<Person1> persons1 = Arrays.asList(new Person1("3","C"),new Person1("1","F"));
Now i want using stream java 8 loop two list and compare. If any object in list persons equal with persons1 , i will create new list and set it with new value. Example : If Person1("1","F") equal Person("1","A") because i using id compare it, i get name from Person1 set to Person. Result : Person("1,"F") and add it two new list.
My code when i using for:
for (Person person : persons) {
for (Person1 person1 : persons1 ) {
if (person1.getId().equals(person.getId())) {
person.setName(person1.getId());
break;
}
}
}
Now i want convert it to Stream with new list look like :
List<Person> personList =
list.stream()
.filter (
person -> list1.stream()
.anyMatch(person1 -> person1.getId()== person.getId()))
.collect(Collectors.toList());
But it only filter person. I want compare two list object. If same id, i want set name from object in persons1 to persons. I know we can using map in stream java 8 but i can't how to do that. Please help