转换Map< String,String>列出< Object>在Java8中

转换Map< String,String>列出< Object>在Java8中

问题描述:

我有返回Map<String,String>且需要转换为DTO的API.

I have API which returns Map<String,String> which needs convert into DTO.

 SubjectIdAndNameDTO (id, name constructor args)
           id
           name

使用传统的for循环和Map.EnterSet的当前实现.我如何使用Java8的功能来简单地执行以下代码.

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);
 }

尝试一下

  map.entrySet()
  .stream()
  .map(m->new SubjectIdAndNameDTO(m.getKey(), m.getValue()))
  .collect(Collectors.toList());

或@Eugene建议使用

or as @Eugene suggested use

 ...collect(Collectors.toCollection(ArrayList::new));

还访问答案.