TreeMap是一个基于key有序的key value散列表。
map根据其键的自然顺序排序,或者根据map创建时提供的Comparator排序
不是线程安全的
key 不可以存入null
底层是基于红黑树实现的
应用场景:可以对对象进行分组(例如商城项目中对购物车中的商品进行分组)
Map<Long, List<OmsCartItem>> productCartMap = new TreeMap<>();
for (OmsCartItem cartItem : cartItemList) {
List<OmsCartItem> productCartItemList = productCartMap.get(cartItem.getProductId());
if (productCartItemList == null) {
productCartItemList = new ArrayList<>();
productCartItemList.add(cartItem);
productCartMap.put(cartItem.getProductId(), productCartItemList);
} else {
productCartItemList.add(cartItem);
}
}
2.获取数据,遍历treeMap
for (Map.Entry<Long, List<OmsCartItem>> entry : productCartMap.entrySet()) {
Long productId = entry.getKey();
PromotionProduct promotionProduct = getPromotionProductById(productId, promotionProductList);
List<OmsCartItem> itemList = entry.getValue();
}