一、合并出共有部分
package com.xu.demo.test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ListMergeTest1 {
public static void main(String[] args) {
List<User> list1 = Arrays.asList(new User(1, "Alice"), new User(2, "Bob"), new User(4, "Ronnie"));
List<User> list2 = Arrays.asList(new User(2, "Bobby"), new User(3, "Charlie"), new User(5, "Trump"));
List<User> mergedList = list1.stream()
.flatMap(user1 -> list2.stream()
.filter(user2 -> user1.getId() == user2.getId())
.map(user2 -> {
User newUser = new User();
newUser.setId(user2.getId());
newUser.setName(user2.getName());
return newUser;
})
)
.collect(Collectors.toList());
mergedList.forEach(System.out::println);
}
}
class User {
private int id;
private String name;
public User(int id, String name) {
this.id = id;
this.name = name;
}
// Getter and Setter methods
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
运行结果:注意流处理中return的位置
二、合并到某一List(假如保留到第一个List)
package com.xu.demo.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListMergeTest2 {
public static void main(String[] args) {
List<Map<String,Object>> list1 = new ArrayList<>();
Map<String,Object> data=new HashMap<>();
data.put("userId","100001");
data.put("userName","唐僧");
list1.add(data);
data=new HashMap<>();
data.put("userId","100002");
data.put("userName","八戒");
list1.add(data);
List<Map<String,Object>> list2 = new ArrayList<>();
data=new HashMap<>();
data.put("userId","100001");
data.put("gender","男");
data.put("age",20);
list2.add(data);
data=new HashMap<>();
data.put("userId","100002");
data.put("gender","雄");
data.put("age",1000);
list2.add(data);
System.out.println(list1);
System.out.println(list2);
//使用stream流把list1和list2根据属性userId合并一个list集合
list1.stream().map(m1 -> {
list2.stream().filter(m2 -> m1.get("userId").equals(m2.get("userId"))).forEach( m2 -> {
m1.put("gender", m2.get("gender"));
m1.put("age", m2.get("age"));
});
return m1;
}).collect(Collectors.toList());
System.out.println(list1);
System.out.println(list2);
}
}
运行结果如下:注意流处理中return的位置
Java8的流式处理提供了大量强大而且简单的数据(结构)处理,一定要好好总结学习,对你的编程思维和能能力的提高大有好处。