我试图找到一种方法,将两个具有两个唯一属性的对象列表连接起来,从而生成一个新的对象列表。
用户类
public class Users {
String id;
String name;
String gender;
}在这里添加一些数据
List<Users> userList=new ArrayList<Users>();
userList.add(new Users("1","AA","Male"));
userList.add(new Users("2","BB","Male"));
userList.add(new Users("3","CC","Female"));学术班
public class Academics {
String id;
String name;
String grade;
String professional;
}在这里添加一些数据
List<Academics> academicsList=new ArrayList<Academics>();
academicsList.add(new Academics("1","AA","A","Doctor"));
academicsList.add(new Academics("2","BB","B","Carpenter"));
academicsList.add(new Academics("3","CC","C","Engineer"));我的个人资料
Public class Profile {
String id;
String name;
String gender;
String grade;
String professional;
}在这里,我需要通过将UserList和academicsList与两个公共属性id和name连接起来来计算列表。
我确实需要作为一个大容量操作来执行这个操作,而不是一个一个地循环任何For/While循环。
有任何方法可以使用流来实现这一点吗?
更新1:这里的连接就像外部连接,其中一些id不会出现在学术中,但是它会出现在用户中。在这种情况下,我们需要显示级别/专业人员个人资料列表的空值。
提前谢谢你,
杰伦
发布于 2018-04-19 06:49:28
将输入列表之一转换为Map是有意义的,以便在第一列表和第二列表的条目之间快速关联。
Map<String,Users> userByID = userList.stream().collect(Collectors.toMap(Users::getID,Function.identity));现在您可以对第二个列表的元素进行流处理:
List<Profile> profiles =
academicsList.stream()
.map(a -> {
Profile p = null;
Users u = userByID.get(a.getID());
if (u != null) {
p = new Profile();
// now set all the Profile fields based on the properties
// of the Users instance (u) and the Academics instance (a)
}
return p;
})
.filter(Objects::nonNull)
.collect(Collectors.toList());考虑到您的额外需求,您应该为第二个List创建一个List,并为第一个List创建一个Stream
Map<String,Academics> academicsByID = userList.stream().collect(Collectors.toMap(Academics::getID,Function.identity));
List<Profile> profiles =
userList.stream()
.map(u -> {
Profile p = new Profile ();
Academics a = academicsByID.get(u.getID());
// now set all the Profile fields based on the properties
// of the Users instance (u) and the Academics instance (a)
// (if available)
return p;
})
.collect(Collectors.toList());https://stackoverflow.com/questions/49914333
复制相似问题