Solution using Hashmap with one iteration.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class User {
String name;
int age;
String address;
public User(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
class Employee{
String name;
int age;
String address;
public Employee(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
public class Test {
public static void main(String args[]) throws Exception {
List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee("Andi",20,"NY"));
empList.add(new Employee("Rob",22,"london"));
empList.add(new Employee("mark",21,"berlin"));
List<User> userList = new ArrayList<>();
userList.add(new User("Andi",20,"NY"));
userList.add(new User("Rob",22,"london"));
userList.add(new User("mark",21,""));
Map<String, Employee> map = empList.stream()
.collect(Collectors.toMap(Employee::getName, employee -> employee));
for(User user : userList){
Employee employee = map.get(user.getName());
if(employee==null){
continue;
}
if(user.getAddress() == null || user.getAddress().equals("")) {
user.setAddress(employee.getAddress());
}
}
userList.forEach(System.out::println);
}
}