以下代码对一共使用了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;
}
}