Database foreach union all query lambda expression, lambda expression

Code

 String accountId = LoginUtils.getLoginAccountId();
log.info("BaseUserCollectInfoServiceImpl.getMerchantInfoList; Start querying the list of favorite merchants accountId: {}", accountId);
PageInfo<BaseMerchantInfoResp> pageInfo = PageHelper.startPage(req.getPageNum(), req.getPageSize())
.doSelectPageInfo(() -> userCollectInfoMapper.getMerchantInfoList(accountId));
if (pageInfo.getTotal() == 0) {
return PageInfoUtils.emptyPageInfo(req);
}
List<BaseMerchantInfoResp> respList = pageInfo.getList();
List<String> accountIds = respList.stream().map(BaseMerchantInfoResp::getAccountId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(accountIds)) {
return pageInfo;
}
//todo queries the merchant service list. Those that are not on the shelves cannot be queried.
List<BaseMerchantServeResp> merchantServeList = userCollectInfoMapper.getBaseMerchantServeList(accountIds);
Map<String, List<BaseMerchantServeResp>> map = merchantServeList.stream().collect(Collectors.groupingBy(BaseMerchantServeResp::getMerchantAccountId, Collectors.toList()));
respList.forEach(e -> {
e.setServeProjectNameList(JSON.parseArray(e.getServeProjectName(), String.class));
e.setMerchantServeList(map.get(e.getAccountId()));
e.setDistance(NumberUtils.getDistance(req.getLongitude(), req.getLatitude(), e.getLongitude(), e.getLatitude()));
});
pageInfo.setList(respList);
return pageInfo;
}

    <select id="getBaseMerchantServeList" resultType="com.first.pet.base.user.vo.BaseMerchantServeResp">
        <foreach item="id" collection="ids" separator="union all">
            (select id,serve_name, serve_type_title,discount_price,merchant_account_id,origin_price from base_merchant_serve where
            merchant_account_id =
            #{id} and yn = 1 and is_show = 'NORMAL' order by id desc limit 2)
        </foreach>
    </select>

Lambda expression null operation

Sometimes, the value of the map you want to get is not an object, but a certain attribute of the object, then you can use the following method:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));
//Check empty and convert map value to attribute
Map<Integer, Integer> brandCountData = brandCount.stream().collect
(Collectors.toMap(e -> e.getBrandId() != null ? e.getBrandId() : 0, BrandCountDTO::getCount, (key1, key2) -> key2));

//Judge value duplication
List<OrderServiceDTO> orderServiceDTOList = orderServiceExport.getOrderServiceDTO(orderIds);
Map<String, OrderServiceDTO> orderServiceDTO = orderServiceDTOList.stream().collect(Collectors.toMap(OrderServiceDTO::getOrderId, o -> o, (old, ne) -> old));
\t\t
//Check empty and convert map value to object
Map<String, List<BrandCountDTO>> brandCountData = brandCount.stream().collect
(Collectors.groupingBy(e -> StringUtils.isNotBlank(e.getBrandId()) ? e.getBrandId() : "", Collectors.toList()));

//Get a value from the object in the collection and return it
  List<ResourceInfoDto> result=new ArrayList<>();
  platformResourceInfoResps.forEach(i->result.add(new ResourceInfoDto().setDesc(i.getTitle()).setId(i.getId())));

//Collection returns assembly object
//First way
List<GoodsSpecification> list = this.lambdaQuery().eq(GoodsSpecification::getGoodsId, id)
.eq(GoodsSpecification::getYn, YnEnums.VALID.getCode()).list();
if (CollectionUtils.isEmpty(list)) {
return Collections.emptyList();
}
List<GoodsSpecificationDetailDataResp> collect = list.stream().map(e ->
{
GoodsSpecificationDetailDataResp resp = BeanUtil.copyBean(e, GoodsSpecificationDetailDataResp.class);
return resp;
}).collect(Collectors.toList());
//Second way
 List<BaseUserInfo> infos = baseUserInfoService.lambdaQuery().
 eq(BaseUserInfo::getYn, YnEnums.VALID.getCode()).in(BaseUserInfo::getAccountId, accountIds).list();
        return infos.stream().map(b -> BeanUtil.copyBean(b, BaseUserNameDTO.class)).
        collect(Collectors.toList());

//list to map
public static void main(String[] args) {
        List<User> userList = Lists.newArrayList();//Storage user object collection

        User user1 = new User(1L, "张三", 24);
        User user2 = new User(2L, "李思", 27);
        User user3 = new User(3L, "王五", 21);

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);

        //ID is key, converted to Map
        Map<Long,User> userMap = userList.stream().collect(Collectors.toMap(User::getId, a -> a,(k1, k2)->k1));
        System.out.println(userMap);
    }

Traverse the map
JDK 8 provides Lambda expression support, its syntax looks more concise, and you can get key and value at the same time.

However, after a simple test, the speed of Lambda expression traversing Map is lower than that of entrySet traversal, so it is more recommended to use entrySet to traverse Map.

    /** Lambda gets key and value */
    public void testLambda() {
        map.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
    }

    Reference link
https://blog.csdn.net/qq_42380734/article/details/105373696

List removes duplicate elements based on the attribute value of the object

 List<Personn> list2 = Arrays.asList
(new Personn("Alice", 25,"123"), new Personn("Charlie", 35,"234"), new Personn("Dave", 40," 345"),
new Personn("Alice", 25,"567"));



ArrayList<Personn> collect1 = list2.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(p->p.getName() + ";" + p.getAge()))), ArrayList::new));

Reference links

List to map, the same value is used as a key, and the list is used as a collection of corresponding objects with the same value

 // Query product information based on order id
        List<String> orderIds = resps.stream().map(OrderGoodsListResp::getOrderId).collect(Collectors.toList());
        List<OrderGoodsItem> orderGoodsItems = orderGoodsItemService.lambdaQuery()
                .in(OrderGoodsItem::getOrderId,orderIds)
                .eq(OrderGoodsItem::getYn, YnEnums.VALID.getCode())
                .list();
        Map<String, List<OrderGoodsInfoResp>> listMap = orderGoodsItems.stream().map(o -> {
            OrderGoodsInfoResp orderGoodsInfoResp = new OrderGoodsInfoResp();
            orderGoodsInfoResp.setGoodsName(o.getGoodsName());
            orderGoodsInfoResp.setPurchaseVolume(o.getPurchaseVolume());
            orderGoodsInfoResp.setOrderId(o.getOrderId());
            orderGoodsInfoResp.setSpecificationName(o.getSpecificationName());
            return orderGoodsInfoResp;
        }).collect(Collectors.groupingBy(OrderGoodsInfoResp::getOrderId));