流集合到其他结构
问题描述:
我尝试将包含列表的对象Dictionary
转换为对象。流集合到其他结构
public class Dictionary {
private String dictCode;
private String dictName;
private String dictDescription;
private String dictElemCode;
private String dictElemName;
private String dictElemDescription;
}
//parent
public class DictDTO {
private String code;
private String value;
private String description;
private List<DictElemDTO> listDictElemDTO;
}
//children
public class DictElemDTO {
private String code;
private String value;
private String description;
}
为Dictionary
类示例数据:
Dictionary d1 = new Dictionary("a1", "dict1", "desc1", "elem_code_1", "elem_code_name", "elem_code_desc");
Dictionary d2 = new Dictionary("a1", "dict1", "desc1", "elem_code_2", "elem_code_name2", "elem_code_desc2");
Dictionary d3 = new Dictionary("a2", "dict2", "desc2", "elem_code_3", "elem_code_name3", "elem_code_desc3");
,并将结果通过这样的:
a1
------ elem_code_1
------ elem_code_2
a2
------ elem_code_3
我对流工程解决方案,但因为我用列表的更多的流很慢比一次。
public static void main(String[] args) {
Dictionary d1 = new Dictionary("a1", "dict1", "desc1", "elem_code_1", "elem_code_name", "elem_code_desc");
Dictionary d2 = new Dictionary("a1", "dict1", "desc1", "elem_code_2", "elem_code_name2", "elem_code_desc2");
Dictionary d3 = new Dictionary("a2", "dict2", "desc2", "elem_code_3", "elem_code_name3", "elem_code_desc3");
List<Dictionary> list = ImmutableList.of(d1, d2, d3);
List<DictDTO> newList = list.stream().filter(distinctByKey(Dictionary::getDictCode)).map(t -> {
DictDTO dto = new DictDTO();
dto.setCode(t.getDictCode());
dto.setValue(t.getDictName());
dto.setDescription(t.getDictDescription());
dto.setListDictElemDTO(
list.stream().filter(e -> e.getDictCode().equals(t.getDictCode())).map(w -> {
DictElemDTO elemDto = new DictElemDTO();
elemDto.setCode(w.getDictElemCode());
elemDto.setValue(w.getDictElemName());
elemDto.setDescription(w.getDictElemDescription());
return elemDto;
}).collect(Collectors.toList())
);
return dto;
}).collect(Collectors.toList());
for (DictDTO dto : newList) {
System.err.println(dto.getCode());
for (DictElemDTO dtoE : dto.getListDictElemDTO()) {
System.err.println("------ " + dtoE.getCode());
}
}
}
static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
什么是在Java 8中使用流这个问题更好的办法?
答
这看起来像Collectors.groupingBy
工作:
Map<String,List<DictElemDTO>>
map = Stream.of(d1,d2,d3)
.collect(Collectors.groupingBy(Dictionary::getDictCode,
Collectors.mapping(d-> new DictElemDTO (d.getDictElemCode(),d.getDictElemName(),d.getDictElemDescription()),
Collectors.toList())));
这会给你的字典代码映射到DictElemDTO
S中的相应列表。
它需要更多的工作来创建DictDTO
对象。
+0
你能为这个问题添加完整的解决方案吗? –
为什么你想使用流呢?我没有看到使用流的很多价值(你只是用它来过滤......) – Lino