3 回答
TA贡献1856条经验 获得超5个赞
你需要这样的东西:
List<ObjectA> firstlist = new ArrayList<>();
firstlist.add(new ObjectA(3, Arrays.asList("test", "test2")));
List<ObjectB> secondList = new ArrayList<>();
secondList.add(new ObjectB("test", 3));
List<ObjectC> result = firstlist.stream()
.flatMap(a -> secondList.stream()
.filter(b -> a.getNames().contains(b.getName()))
.map(c -> new ObjectC(a.getId(), c.getName(), c.getAge()))
).collect(Collectors.toList());
如果我理解你的问题,你有三个不同的对象,如下所示:
@Getter @Setter @AllArgsConstructor @NoArgsConstructor
public class ObjectA {
private int id;
private List<String> names;
}
@Getter @Setter @AllArgsConstructor @NoArgsConstructor
public class ObjectB {
private String name;
private int age;
}
//And the result Object you want to get
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString
public class ObjectC {
private int id;
private String name;
private int age;
}
这个例子的输出是:
[ObjectC(id=3, name=test, age=3)]
对于注释,我使用 Lombok
TA贡献1936条经验 获得超6个赞
您可能需要以下内容:
List<ClassWithId> list1 = new ArrayList<>();
List<ClassWithAge> list2 = new ArrayList<>();
list1.add(new ClassWithId(3, Arrays.asList("test", "test2")));
list2.add(new ClassWithAge("test", 4));
List<ClassResult> list3 = list2.stream()
.map(i -> new ClassResult(
list1.stream()
.filter(j -> j.getList().contains(i.getName()))
.map(j -> j.getId())
.findFirst().get(),
i.getName(), i.getAge()))
.collect(Collectors.toList());
此解决方案假定以下两个输入对象和输出对象的结构:
带标识的类
private int id;
private List<String> list;
年龄分类
private String name;
private int age;
类结果
private int id;
private int age;
private String name;
添加回答
举报