lambda表达式对两个List进行循环,根据符合条件,进行相关的赋值操作并返回这个对象集合

首先创建两个对象男生和女生:

// 男生 get set和toString这里省略
public class SchoolBoy {
	private String girlId;
	
	private String id;
	
	private String name;

	private String grilName;
}
// 女生 get set和toString这里省略
public class Girl {
	private String id;

	private String name;
}

根据男生对象中的girlId去匹配女生对象并把男生对象的grilName字段赋值

下面展示一个demo

public static void main(String[] args) {
	List schoolBoys = new ArrayList<>(3);
	SchoolBoy boy1 = new SchoolBoy();
	boy1.setGirlId("1");
	boy1.setId("10");
	boy1.setName("小明");

	SchoolBoy boy2 = new SchoolBoy();
	boy2.setGirlId("2");
	boy2.setId("11");
	boy2.setName("小豪");

	SchoolBoy boy3 = new SchoolBoy();
	boy3.setGirlId("3");
	boy3.setId("12");
	boy3.setName("小白");
	schoolBoys.add(boy1);
	schoolBoys.add(boy2);
	schoolBoys.add(boy3);

	List girls = new ArrayList<>(3);
	Girl girl1 = new Girl();
	girl1.setId("1");
	girl1.setName("小英");

	Girl girl2 = new Girl();
	girl2.setId("2");
	girl2.setName("小美");

	Girl girl3 = new Girl();
	girl3.setId("3");
	girl3.setName("小花");
	girls.add(girl1);
	girls.add(girl2);
	girls.add(girl3);
	
	List list = schoolBoys.stream()
		.map(schoolBoy -> girls.stream()
				.filter(girl -> schoolBoy.getGirlId().equals(girl.getId()))
				.findFirst()
				.map(girl -> {
					schoolBoy.setGrilName(girl.getName());
					return schoolBoy;
				}).orElse(null))
		.collect(Collectors.toList());
	System.out.println(list.toString());
}

最后执行的结果:

[SchoolBoy [girlId=1, id=10, name=小明, grilName=小英],

SchoolBoy [girlId=2, id=11, name=小豪, grilName=小美],

SchoolBoy [girlId=3, id=12, name=小白, grilName=小花]]
如果lambda有更好的处理方式或者上面代码有错误的地方,请评论中指出,感谢!

你可能感兴趣的:(开发中需要的)