반응형

작성일자 : 2020.06.13

 

Stream 을 활용하여 List to Map 변환하는 과정에서 발생할 수 있는 키 중복 예외

 

예외 발생 예시

List<Integer> list = new ArrayList<Integer>(){{add(0);add(1);add(1);add(2);}};
// { 0, 1, 1, 2 }
        
        
Map<Integer, Integer> map = list.stream()
       .collect(Collectors.toMap(vo->vo, vo->vo));
// { {0,0}, {1,1}, {1,1}, {2,2} } 형태로 반환 -> key 1 중복 !!

 

수정

List<Integer> list = new ArrayList<Integer>(){{add(0);add(1);add(1);add(2);}};
// { 0, 1, 1, 2 }
        
        
Map<Integer, Integer> map = list.stream()
       .collect(Collectors.toMap(vo->vo, vo->vo, (oldValue, newValue) -> oldValue));
// { {0,0}, {1,1}, {2,2} } 형태로 반환 

// 기존 값을 유지할 경우
// .collect(Collectors.toMap(vo->vo, vo->vo, (oldValue, newValue) -> oldValue));
// 새로운 값을 유지할 경우
// .collect(Collectors.toMap(vo->vo, vo->vo, (oldValue, newValue) -> newValue));
반응형

+ Recent posts