1. 程式人生 > >Java 8中stream相關用法

Java 8中stream相關用法

jdk1.8新加了lambda表示式,可以幫助開發者更好的,更高效的實現一些通常複雜的程式碼實現

1.list轉換map

Map<Integer, String> mappedMovies = ghslist.stream().collect( Collectors.toMap(SaleStaticsGhsResp::getShop_saleman_id, (p) -> p.getName()));
2.從實體中取出id集合,去重

List<Integer> list = page.stream().filter(m->m.getId()>0).map(k -> k.getId()).distinct().collect(Collectors.toList());
3.遍歷一個list,和另一個list對比,取出id相同的每個實體

SaleMan sale = saleList.stream().filter(e -> e.getId().intValue() == olm.getSm_saleman_id()).findFirst().orElse(null);
4.排序(先按第一個欄位排序,如果排序欄位相等,在按第二個欄位排序)

Comparator<SpreadActivityResp> comparator0 =(b, a) -> a.getCreate_time().compareTo(b.getCreate_time());
 
resultList.sort(comparator0);
 
Comparator<SpreadActivityResp> comparator = comparator0.thenComparing((a,b) -> b.getCreate_time().compareTo(a.getCreate_time()));
 
for (CartGoodsInfo info : shop.getGoodsInfoList()) {
 
    cartList.add(info.getCartInfo());
 
    info.getPriceInfoList().sort((a, b) -> {
 
    return a.getMinCount().compareTo(b.getMinCount());
 
});
 
priceList.addAll(info.getPriceInfoList());
 
}
 
list_order_goods.sort((a,b)->{return Integer.valueOf(a.getId()).compareTo(b.getId());});
5.根據某個id獲取list中和這個id相同的實體

List<Price> pricelist = pricesList.stream().filter(k -> {return skuListId.contains(k.getSku_id());}).collect(Collectors.toList());
 
List<SearchOrderGoodsResp> unzpList = list_order_goods.stream().filter(m->m.getIs_giveaway() == 0).distinct().collect(Collectors.toList());
 
--------------------- 
作者:yinghuananhai 
來源:CSDN 
原文:https://blog.csdn.net/YingHuaNanHai/article/details/81273059 
版權宣告:本文為博主原創文章,轉載請附上博文連結!