본문 바로가기
Java/series

[Java 7편] stream list to map<String, Dto>

by 무대포 개발자 2022. 8. 31.
728x90
반응형

source 는 Github 에 있습니다.

목차는 Java series 에 있습니다.

[Java 7편] stream list to map<String, Dto>

Stream List to Map<String, DTO>

  • list 를 Map<String, DTO> 변환하는 예제를 정리했습니다.

Source

public class StreamListToMapObjectTest {
@Test
@DisplayName("list를Map<String, DTO> 변환")
public void streamListToMapObjectTest01() throws Exception {
List<DtoA> list = new ArrayList<>();
list.add(new DtoA("key1", "bcde"));
list.add(new DtoA("key2", "bcde123"));
Map<String, DtoB> map =
list.stream().map(a -> new DtoB(a.getKey(), a.getValue()))
.collect(Collectors.toMap(DtoB::getKey, Function.identity()));
Assertions.assertEquals(2, map.keySet().size());
Assertions.assertEquals("bcde", map.get("key1").getValue());
Assertions.assertEquals("key1", map.get("key1").getKey());
}
private static class DtoA {
private String key;
private String value;
public DtoA(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
private static class DtoB {
private String key;
private String value;
public DtoB(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
}

댓글