问题
I have API which returns Map<String,String>
which needs convert into DTO.
SubjectIdAndNameDTO (id, name constructor args)
id
name
current implementation using traditional for loop and Map.EnterSet. How can i use feature of Java8 to simply the following code.
Map<String, String> map = getSubjectIdAndNameMap();
// How can this code can be improved by using Java8 Stream and method references
List<SubjectIdAndNameDTO> subIdNameDTOList = new ArrayList<>();
for (Entry<String, String> keyset : map.entrySet()) {
SubjectIdAndNameDTO subjectIdNameDTO =
new SubjectIdAndNameDTO(keyset.getKey(), keyset.getValue());
subIdNameDTOList.add(subjectIdNameDTO);
}
回答1:
Try this
map.entrySet()
.stream()
.map(m->new SubjectIdAndNameDTO(m.getKey(), m.getValue()))
.collect(Collectors.toList());
or as @Eugene suggested use
...collect(Collectors.toCollection(ArrayList::new));
also visit this answer.
来源:https://stackoverflow.com/questions/49030336/converting-mapstring-string-to-listobject-in-java8