猿问

将 List<Object[]> 转换为 List<MyClass>

 List<Object[]> listChild = query.list();

 List<ChildrenDTO> listOfDTO = new ArrayList<>();


 //Loop through arraylits of object

 for(Object[] org: listOrg){

      //How to cast List of object to ist<ChildrenDTO>?

     listOfDTO.add(org);

 }

我正在遍历对象列表并需要返回 listOfDTO。如何将列表转换为列表?


收到一只叮咚
浏览 277回答 3
3回答

翻过高山走不出你

如果您使用 java 8,则应该尝试使用流 api。考虑到 DTO 的构造函数有一个String参数。List<Object[]> listChild = query.list();List<ChildrenDTO> children = listChild.stream().map(x -> new ChildrenDTO(x[0].toString())).collect(Collectors.toList());

慕哥6287543

因此,首先,您要遍历包含对象数组的 List。因此,要获取每个单独的对象,您需要有一个嵌套循环,例如:&nbsp; &nbsp; &nbsp; &nbsp; for (Object[] org : listOrg) {&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < org.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (org[i] instanceof ChildrenDTO) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listOfDTO.add((ChildrenDTO) org[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }我不是 100% 确定您是否可以将对象强制转换为 ChildrenDTO 对象,但如果不能,您可以只获取对象值并创建一个新的 ChildrenDTO 实例,也许是一个构造函数来获取对象值?

HUH函数

您可以使用Java 8 流 API:List<Object[]>&nbsp;listChild&nbsp;=&nbsp;...List<ChildrenDTO>&nbsp;childrenDtos&nbsp;=&nbsp;listChild.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.flatMap(Arrays::stream) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(object&nbsp;->&nbsp;Objects.equals(object.getClass(),ChildrenDTO.class)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//.filter(object&nbsp;->&nbsp;object&nbsp;instanceof&nbsp;ChildrenDTO)&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//instead&nbsp;of&nbsp;Objects.equals(class,&nbsp;class),&nbsp;if&nbsp;required &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(object&nbsp;->&nbsp;(ChildrenDTO)object) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());
随时随地看视频慕课网APP

相关分类

Java
我要回答