记录Map、Optional、Lambda 使用

以下代码对一共使用了Map、Optional、Lambda几种用法。
实体对象:


@Data
public class TeamBuyingChildDTO implements Serializable {
  /**
   * 商品Id
   */
  @ApiModelProperty(value = "商品Id", required = true)
  @NotNull
  private Long productId;

  /**
   * 单个拼团包含的数量
   */
  @NotNull
  @ApiModelProperty(value = "单个拼团包含的数量", required = true)
  private Integer teamMemberJoinCount;
  /**
   * 可用库存
   */
  @ApiModelProperty(value = "可用库存", required = true)
  private Integer productCount;
  /**
   * 团员价格
   */
  @NotNull
  @ApiModelProperty(value = "团员价格", required = true)
  private BigDecimal teamMemberPrice;
  /**
   * 团长价格
   */
  @ApiModelProperty(value = "团长价格")
  private BigDecimal teamLeaderPrice;
}

Map代码:

Map<Long, BigDecimal> minPrices = Maps.newLinkedHashMap();
minPrices.put(childenProduct.getProductId(), minTeamPrice);

Map<Long, TeamBuyingChildDTO > childenProductMaps = Maps.newLinkedHashMap();
childenProductMaps.put(childenProduct.getProductId(), childenProduct);

Optional代码:还对Map进行排序取第一个值了

    Optional<Map.Entry<Long, BigDecimal>> min = minPrices.entrySet().stream()
        .sorted((c, d) -> c.getValue().compareTo(d.getValue())).findFirst();
    if (min.isPresent()) {
      return childenProductMaps.get(min.get().getKey());
    } else {
      return null;
    }

总代码:

  private TeamBuyingChildDTO getMinPrice(List<TeamBuyingChildDTO > childenProducts) {
    Map<Long, BigDecimal> minPrices = Maps.newLinkedHashMap();
    Map<Long, InsertTeamBuyingChildDTO> childenProductMaps = Maps.newLinkedHashMap();
    for (TeamBuyingChildDTO  childenProduct : childenProducts) {
      BigDecimal minTeamPrice = BigDecimal.ZERO;
      if (childenProduct.getTeamLeaderPrice() == null) {
        minTeamPrice = childenProduct.getTeamMemberPrice();
      } else {
        minTeamPrice = MoneyUtil.smallerThan(childenProduct.getTeamLeaderPrice(),
            childenProduct.getTeamMemberPrice()) ? childenProduct.getTeamLeaderPrice()
                : childenProduct.getTeamMemberPrice();
      }
      minTeamPrice = minTeamPrice.multiply(new BigDecimal(childenProduct.getTeamMemberJoinCount()));
      minPrices.put(childenProduct.getProductId(), minTeamPrice);
      childenProductMaps.put(childenProduct.getProductId(), childenProduct);
    }

    Optional<Map.Entry<Long, BigDecimal>> min = minPrices.entrySet().stream()
        .sorted((c, d) -> c.getValue().compareTo(d.getValue())).findFirst();
    if (min.isPresent()) {
      return childenProductMaps.get(min.get().getKey());
    } else {
      return null;
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值