2023-java-study / book-study

북 스터디 기록 레포지토리
0 stars 0 forks source link

[Item46] 스트림 원소 다수가 같은키를 사용할 때 #137

Open ssstopeun opened 1 year ago

ssstopeun commented 1 year ago

p.280 코드 46-4

스트림 원소 다수가 같은 키를 사용한다면 파이프라인이 IllegalStateException을 던지며 종료될 것이다.

코드 46-4를 사용했을 때 다음과 같은 상황이 안 와닿아서 예시를 보고 싶습니다!

gmelon commented 1 year ago

예를 들어 아래와 같은 코드가 있다고 할 때, (arr1은 중복되는 원소가 없으므로 enum과 같은 상태이고, arr2는 "d"라는 원소가 중복되도록 했습니다)

List<String> arr1 = List.of("a", "b", "c", "d");
Map<String, String> map1 = arr1.stream()
        .collect(toMap(Object::toString, s -> s));

List<String> arr2 = List.of("a", "b", "c", "d", "d");
Map<String, String> map2 = arr2.stream()
        .collect(toMap(Object::toString, s -> s));

map1은 정상적으로 만들어지지만, map2 생성 시 아래와 같은 오류가 출력됩니다.

image

읽어보면, "d" 키가 중복되었는데 우리가 toMap()에 이를 merge할 방법을 제시하지 않았기 때문에 못만들어! 하고 팅겨버린 것을 알 수 있습니다.

이를 해결하려면 아래와 같이 BinaryFunction 타입의 mergeFunction을 toMap() 함수의 3번째 인자로 전달해주면 됩니다.

List<String> arr2 = List.of("a", "b", "c", "d", "d");
Map<String, String> map2 = arr2.stream()
        .collect(toMap(Object::toString, s -> s, (value1, value2) -> value1 + value2));

// map2
// {a=a, b=b, c=c, d=dd}