簡體   English   中英

如何過濾 Hashmap 以使用 Java 8 stream 即時更新值?

[英]How to filter Hashmap to update the value on the fly using Java 8 stream?

我有一個場景,我不確定過濾 hashmap 並更新相同的 map 的有效方法可能是什么。 這是我的 hashmap; Map<Double, List<Product>> mappedProducts = new HashMap<>(); 我已經以某種方法在 mappedProducts 中列出了鍵和值。 現在在另一種方法中,我試圖根據我的鍵值是否大於產品的屬性權重來過濾掉產品列表。 我就是這樣做的,雖然它工作得很好,但我不確定這是否是最有效和最有效的方法。 看看下面的代碼;

this.mappedProducts.entrySet().stream().filter(packList ->{
        mappedProducts.put(packList.getKey(), packList.getValue().stream().filter(pack ->{
                if(pack.getWeight() <= packList.getKey())
                    return true;
                return false;
        }).collect(Collectors.toList()));
        return true;
    }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println("Filtered Products"+mappedProducts);

還有其他更好的方法來完成這項工作嗎?

如果您想要過濾后的新 map:保留所有產品重量小於密鑰的條目

Map<Double, List<Product>> filtered = mappedProducts.entrySet()
        .stream()
        .filter(packList -> packList.getValue().stream().allMatch(pack -> pack.getWeight() < packList.getKey()))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

如果要修改主map:刪除其中一個產品重量高於密鑰的所有條目

mappedProducts.entrySet()
              .removeIf(packList -> packList.getValue().stream().anyMatch(pack -> pack.getWeight() > packList.getKey()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM