我想将 Java 8 流用于以下实现。基本上我想解析一个列表并形成另一个不同对象的列表。
输入 - Person pojos 列表,
输出 - PersonInfo pojo 列表
List<Person> persons = new ArrayList<Person>();
Person max = new Person();
max.setName("Max");
max.setAge(10);
max.addAddress(new Address("Street1", "City1"));
max.addAddress(new Address("Street2", "City2"));
Person peter = new Person();
peter.setName("Peter");
peter.setAge(20);
peter.addAddress(new Address("Street1", "City1"));
peter.addAddress(new Address("Street2", "City2"));
persons.add(max);
persons.add(peter);
System.out.println("Input: " + persons);
List<PersonInfo> personInfos = new ArrayList<PersonInfo>();
PersonInfo personInfo = null;
for (Person person : persons) {
for (Address addr : person.getCurrAndPrevAddrs()) {
personInfo = new PersonInfo();
personInfo.setName(person.getName());
personInfo.setAge(person.getAge());
personInfo.setAddrs(addr);
personInfos.add(personInfo);
}
}
System.out.println("Output: " + personInfos.toString());
示例输出 :
输入 : [最大 10 [Street1 City1, Street2 City2]
, 彼得 20 [Street1 City1, Street2 City2]]
输出 : [最大 10 Street1 City1
, 最大 10 Street2 City2
, Peter 20 Street1 City1
, 彼得 20 Street2 City2]
最佳答案
List<PersonInfo> personInfos = persons.stream().flatMap(person -> person.getCurrAndPrevAddrs().stream().map(addr -> {
PersonInfo personInfo = new PersonInfo();
personInfo.setName(person.getName());
personInfo.setAge(person.getAge());
personInfo.setAddrs(addr);
return personInfo;
})).collect(Collectors.toList());