본문 바로가기
개발

Java - Collectors.toMap()

by 플리트우드 2024. 12. 5.

출처 : https://motti.tistory.com/entry/Java8-Stream%EC%97%B0%EC%82%B0%EC%9D%84-%EC%82%AC%EC%9A%A9%ED%95%B4%EB%B3%B4%EC%9E%90

 

Java8 스트림(Stream)연산을 사용해보자

Stream(스트림)연산컬렉션을 처리할때 보통은 요소들을 첨부터 끝까지 순회하면서 각 요소를 대상으로 작업한다. 하지만, Java8 부터는 스트림연산을 통해 반복하지 않아도 된다.List word;int count = 0;

motti.tistory.com

 

 

 

Stream<Person>의 요소들을 맵으로 모아서 추후 ID로 사람을 조회할 수 있게 하려 한다고 하자. Collectors.toMap 메서드는 각각 맵의 키와 값을 생산하는 두 함수 인자를 받는다. 예를 들면, 다음과 같다.

 

Map<Integer, String> idToName = people.collect(

Collectors.toMap(Person::getId, Person::getName));


 

값이 실제 요소여야 하는 일반적인 경우에서는 두 번째 함수로 Function.identity()를 사용한다.

Map<Integer, Person> idToPerson = people.collect(

Collectors.toMap(Person::getId, Function.identity()));




성질이 같은 값들의 그룹을 만드는 일은 아주 흔한 작업으로, 

groupingBy 메서드는 그룹 작업을 직접 지원한다.

로케일을 국가별로 묶는 문제를 살펴보자. 먼저 다음과 같은 맵을 만든다.

Map<String, List<Locale>> countryToLocales = locales.collect(

Collectors.groupingBy(Locale::getCountry));

'개발' 카테고리의 다른 글

자바 DB 커넥션 리소스 정리  (0) 2024.12.06
Lombok  (0) 2024.12.05
Hashing  (0) 2024.12.05
Intellij에서 jUnit Test  (0) 2024.12.05
리눅스 - grep, find, netstat, lsof, chmod  (0) 2024.12.05