基本上我有以下代码:
List<Object[]> tes = new ArrayList<>();
Object[] ar1 = {"John","Cena","2347867686"};
Object[] ar2 = {"Peter","Smith","978787878"};
tes.add(ar1);
tes.add(ar2);
我有以下PersonDto类,如下所示:
public class PersonDto {
String name;
String surname;
String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
这就是我的尝试:
for (Object[] object : tes) {
TestDto testDto = new TestDto();
for (Object object2 : object) {
System.out.println(object2);
}
System.out.println("second");
}
但我无法知道何时在for循环中设置姓氏,姓名或电话。 所以基本上我试图将每个数组映射到列表中的PersonDto,如下所示:
所以预期的结果是:
列表中可以有许多数组,每个数组都有三个属性(名称,姓氏,电话)。
答案 0 :(得分:4)
如果你的PersonDto
有一个构造函数会更容易:
PersonDto(String name, String surname, String phone) {
this.name = name;
this.surname = surname;
this.phone = phone;
}
然后,只需称呼它:
List<PersonDTO> =
objets.stream()
.map(arr -> new PersonDTO((String) arr[0], (String) arr[1], (String) arr[2]))
.collect(Collector.toList());
答案 1 :(得分:3)
public PersonDto (String name, String surname, String phone){
this.name = name;
this.surname = surname;
this.phone = phone;
}
public PersonDto buildPersonDto(Object[] info){
return new PersonDto((String)info[0], (String)info[1], (String)info[2]);
}
public List<PersonDto> convertList(ArrayList<Object[]> people){
ArrayList<PersonDto> result = new ArrayList<>();
for(Object[] person : people)
result.add(buildPersonDto(person));
return result;
}