Java8 two lists take the intersection according to a certain attribute

class User {

public User(Integer id, String name) {

this.id = id;

this.name = name;

}

private Integer id;

private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public String toString() {

return "id =" + id + ", name = " + name;

}

}

public class Demo {

private static User find(Integer id, List<User> list) {

User user = null;

for (int i = 0; i < list.size(); i++) {

if (id.equals(list.get(i).getId())) {

user = list.get(i);

}

}

return user;

}

public static void main(String[] args) {

List<User> list1 = Arrays.asList(new User(1, "小明"), new User(2, "小花"), new User(3, "小华"), new User(4, "小东"));

List<User> list2 = Arrays.asList(new User(1, "小明2"), new User(2, "小花2"), new User(3, "小华2"));

List<User> result = list1.parallelStream().map( user ->{

User user1 = list2.stream().filter(u -> u.getId().equals(user.getId())).findFirst().orElse(null);

if(null != user1){

user.setName(user1.getName());

}

return user;

}).collect(Collectors.toList());

Guess you like

Origin blog.csdn.net/m1195900241/article/details/124970052