개발/JAVA

[Java] List를 map(배열같은key/value) 로 만들기

여름청춘 2023. 8. 30. 19:51
결론
Collectors.toMap 를 사용하자

 

과정

List<Shop> shops 로 매장리스트를 가져오고 

Key = shop_id 

Value = Shop shop 

 

이렇게 map을 만들어서 key 로 해당 객체를 이용할 수 있는 방법이 필요했다. 

 

  @Transactional
  public void setDefaultSyncEnabledBulk(List<ShopProductDto> shopProductDtos) {
    Map<Long, Shop> shopMap = shopService.getAllShop()
        .stream()
        .collect(Collectors.toMap(shop -> shop.getId(), shop -> shop));

    // bulk insert
    List<ShopProduct> shopProducts = shopProductDtos.stream()
        .map(shopProductDto -> {
          shopProductDto.validation();

          return ShopProduct.builder()
              .shop(shopMap.get(shopProductDto.getShopId()))
              .goodsId(shopProductDto.getGoodsId())
              .businessModelType(shopProductDto.getBusinessModelType())
              .syncEnabled(shopProductDto.getSyncEnabled())
              .build();
        })
        .filter(Objects::nonNull)
        .toList();

    // shop_product bulk insert
    shopService.saveAll(shopProducts);
  }

 

해당 로직의 설명을 덧붙이자면 

ShopProduct를 빌드할때 shopId 에 맞는 shop 객체를 주입시켜 주어야 했다. 
stream 을 돌릴때마다 조회할 수는 없으므로 
shop 리스트를 map 으로 만들어 shopId를 key 값으로 이용할 수 있게 

shopMap.get(shopProductDto.getShopId()

이렇게 구현 ! 

 

 

 

collect 의 기능을 조금더 알아보자
    Map<String, Integer> filterMap = shopProducts.stream()
        .collect(Collectors.toMap(
            shopProduct -> GoodsUtil.makeKey(shopProduct.getShop().getId(), shopProduct.getGoodsId()),
            shopProduct -> 1,
            (o, n) -> o
        ));
Collectors.toMap 에는 세번쨰 인자가 있다. 
첫번째 인자는  key 로 넣을 값
두번째 인자는 value로 넣을 값
세번째 인자는 old 와 new 가 있으면 어떤 값으로 넣을지 (기존값을 유지할지, 새로운값으로 업데이트 할지를 결정할 수 있다. 
(old, new) -> old : value 값에 변동이 있을시 기존값 유지  

(old, new) -> new : value 값에 변동이 있을시 새로운 값으로 업데이트 

 

 

 

    Map<Long, Shop> shopMap = shopService.getAllShop()
        .stream()
        .collect(Collectors.toMap(shop -> shop.getId(), shop -> shop));

여기서는 key의 타입이 Long, value의 타입은 Shop 객체  

 

    Map<String, Integer> filterMap = shopProducts.stream()
        .collect(Collectors.toMap(
            shopProduct -> GoodsUtil.makeKey(shopProduct.getShop().getId(), shopProduct.getGoodsId()),
            shopProduct -> 1,
            (o, n) -> o
        ));

여기서는 key의 타입이 String, value의 타입은 Integer 객체