java8對集合的操作等

我們在操作集合時,可能會遇到很多複雜的業務邏輯,這時候可能會嵌套n層循環來實現邏輯功能,但是我們用java8的lambda來操作集合的話相比較來說會肥腸簡單:

//選取符合一定條件的新list

List<ImportAttributeValue> inserts = groupAttributeValues

.stream()
.filter(it -> !groupBaseAttributes.containsKey(it.getAttributeName()))
.collect(Collectors.toList());


// 直接獲取map中相應的集合,性能很快
        List<Long> target = categories.get(level);
        // 根據父類目獲取相應的子類目信息,之前寫好的方法
        List<CategoryResult> children = getPlatformCategoryByParentId(platformId, parentCategoryId);
        List<CategoryResult> result = children
.stream()
                // 子類目中篩選相應的審覈通過的類目,包含其類目ID信息
                .filter(it -> target.contains(it.getCid()))
                // 聚合成集合進行返回
                .collect(Collectors.toList());
        return result;


//取商品ID集合(爲批量查詢商品銷量做準備)
        if (retList != null && retList.size() > 0){
            itemIds = retList.stream()
                    .map(it -> it.getItemId())
                    .collect(Collectors.toList());

        }


        List<Long> picSkus = list.stream()
                .map(it -> it.getSkuId())
                .distinct()
                .collect(Collectors.toList());

//過濾之後組裝新list然後再遍歷

platformCategoryAttributeList.parallelStream()
                .filter(it -> attrIdList.contains(it.getId()))
                .collect(Collectors.toList())
                .parallelStream()
                .forEach(it -> {
                    Map<String,Object> column = new HashedMap();
                    column.put("id", it.getAttrId());
                    column.put("name",it.getAttrName());
                    columnAttributeList.add(column);
                });


//循環運行多條語句,函數式forEach

platformCategoryAttribute.getPlatformCategoryAttributeValues()

.stream()

.forEach(it -> {

it.setAttrId(platformCategoryAttribute.getId());

it.setAttrValueId(it.getId());

}

);


//List  的 addAll 的方法 (取兩個list 的並集)

listA.addAll(listB)

首先兩邊都不允許爲null

但是允許兩邊爲size等於0的實例,也會進行取並集操作


//過濾並取得符合相應條件的對象

ShopItemAnnex itemPicture = shopItemAnniceList.stream()
                .filter(it -> 1 == it.getSortNumber())
                .findFirst()
                .get();


//下面介紹一下一個對集合進行判斷的方法

hasInventory = !skuInventoryList.stream()
                    .anyMatch(it -> (null == it || it < 1));

此方法返回布爾值,只要滿足其中一個就會返回true,當然還有allMatch方法,全部滿足纔會返回true


//下面介紹講List轉化爲Map的方法

Map<Long, String> collect = itemList.stream().collect(HashMap::new, (m,v)->m.put(v.getId(), v.getItemName()), HashMap::putAll);

此方法是講item對象集合中的id與itemName轉化爲map集合,允許重複的鍵,也允許value中存在null值,但是Collectors.toMap方法不允許有重複的鍵,也不允許有value爲null,向下面代碼,我們需要做多餘的代碼來判斷重複與null, Map<Long, String> result = items.stream().collect(Collectors.toMap(Item::getId, Item::getItemName, (key1, key2) -> key2, TreeMap::new));

Map<Long, ItemSkuPictureVo> collect = itemSkuPictureVoList.stream().filter(it -> null != it.getSkuId())

                    .collect(Collectors.toMap(ItemSkuPictureVo::getSkuId, it -> it, (x, y) -> x));


Map<Long, ShopItemSku> skuMap = itemSkus.stream()

                .collect(Collectors.toMap(ShopItemSku::getId, it -> it));

注:list使用Collectors.toMap轉換爲map  若key值相同時處理,使用函數來選擇比較使用舊值還是新值

List<PlatformCategoryAttributeValue> origin = null

logger.info("排重店鋪的銷售屬性值問題:{}", origin);
        BinaryOperator<PlatformCategoryAttributeValue> operator = (existingValue, newValue) ->{
            // 當key重複時候,使用平臺值
            if(new Integer(1).equals(existingValue.getFromType())) {
                return existingValue;
            }
            return newValue;
        };

        Map<String, PlatformCategoryAttributeValue> mapResult = origin.stream()
                .collect(Collectors.toMap(PlatformCategoryAttributeValue::getAttrValueName, it-> it, operator));



//對於map的循環

mapping.forEach((k, v) -> {
            if(!result.containsKey(k)) {
                inserts.add(v);
            }
        });

//下面介紹List的retailAll()方法

list3.retainAll(list1)

首先, 這個retainAll 方法的作用是 :
java.util.ArrayList.retainAll(Collection<?> collection)
僅保留此collection中那些也包含在指定collection的元素(可選操作)。
換句話說,移除此collection中未包含在指定collection中的所有元素。
此實現在此collection上進行迭代,依次檢查該迭代器返回的每個元素,以查看其是否包含在指定的

collection中。如果不是,則使用迭代器的remove方法將其從此collection中移除。
返回值的意思是這樣的,如果此 collection 由於調用而發生更改,則返回 true

在此,你這個list3 和list1 裏面元素的內容 其實是一樣的, 這樣一來,調用 list3.retainAll(list1) 時候
,發現,不需要從list3中去除不在list1中的元素,因此這個list3不需要發生更改,那麼返回值就是是
false,也就是說,這個方法的返回值是標識list3 有沒有改變,而不是這個方法是否執行正常或者成功

JDK1.6 這個方法的 源碼
public boolean retainAll(Collection<?> c){
    boolean modified = false;
    Iterator<E> e = iterator();
    while (e.hasNext()){
        if (!c.contains(e.next())){
            e.remove();
            modified = true;
        }
    }
    return modified;

}

//集合的排序

    第一種實現Comparator接口,實現compare方法來進行排序
    //排序List<Obiect>
    private List<PlatformCategoryAttribute> sort(List<PlatformCategoryAttribute> platformCategoryAttributes) {

        Collections.sort(platformCategoryAttributes, new Comparator<PlatformCategoryAttribute>() {
            @Override
            public int compare(PlatformCategoryAttribute o1, PlatformCategoryAttribute o2) {
                Long i = o1.getAttrId() - o2.getAttrId();
                return i.intValue();
            }
        });
        for (PlatformCategoryAttribute platformCategoryAttribute : platformCategoryAttributes){
            List<PlatformCategoryAttributeValue> values = platformCategoryAttribute.getPlatformCategoryAttributeValues();
            if (values != null && values.size() > 1){
                Collections.sort(values, new Comparator<PlatformCategoryAttributeValue>() {
                    @Override
                    public int compare(PlatformCategoryAttributeValue p1, PlatformCategoryAttributeValue p2) {
                        Long ii = p1.getAttrValueId() - p2.getAttrValueId();
                        return ii.intValue();
                    }
                });
            }
        }
        return platformCategoryAttributes;
    }

    注:屬性id和屬性值id是一對多的關係


下面是java8對於集合的排序:

    一、list排序

    List<Integer> list = Arrays.asList(new Integer[]{1,9,4,6,2,7,5,3});  //構造list,填充值

    list  = list .stream().sorted((n1,n2)->n1.compareTo(n2)).collect(Collectors.toList());

    "->"左邊是入參,右邊是具體的比較操作,然後將結果通過collect返回.

    二、map排序

    Map<String, Integer> unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("b", 5);
    unsortMap.put("a", 6);
    Map<String, Integer> result2 = new LinkedHashMap<>();

    List<ItemBrandVo> finalList= new ArrayList<>();

    2)、Map<String, Integer> result = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                 (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    將map(HashMap)對象包裝成 Stream 後調用.sorted排序,通過Key值比較,然後用.collect收集爲LinkedHashMap,此重載收集器一共四個參數,第一值是指key值,第二個是指value值,第三個是指鍵值映射關係,第四個是指新的容器的實體


    2)、unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
    將map(HashMap)對象包裝成 Stream 後調用.sorted排序,通過Key值比較,然後將每一組鍵值對進行相應.forEachOrdered操作,此處是將每一組的鍵和值重新裝入新的結果中(LinkedHashMap)


    3)、specialListMap.entrySet().stream()
                    .sorted(Map.Entry.<String, List<ItemBrandVo>>comparingByKey())
                    .forEachOrdered(e -> e.getValue().forEach(finalMap::add));
    將map(HashMap)對象包裝成 Stream 後調用.sorted排序,通過Key值比較,然後將每一組鍵值對進行相應.forEachOrdered操作,此處是將每一組的值重新裝入finalList中


還有諸如 map.containsKey(stringKey),

list1.contains(object1),注:(注意需要重寫equals方法)

list1.containsAll(list2)



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章