簡體   English   中英

Java stream 收集到ConcurrentHashMap錯誤

[英]Java stream collect toConcurrentHashMap error

我有以下 stream ,它接受每個聯系人,並且應該創建一個 ConcurrentHashMap ,其中每個聯系人的 id 作為鍵,一個空的 Optional 作為值。 我嘗試使用整理器以正確的形式生成 Map,因為沒有它會出現類型不匹配,因為未鍵入 Optional。 使用以下代碼,我在倒數第二個括號中得到 '(' 或 '[' 。

ConcurrentHashMap<Integer, Optional<BlockingQueue<Packet>>> channelMap = 
contacts.stream().collect(
    Collectors.collectingAndThen(
        Collectors.toConcurrentMap(
            Contact::getCid, s -> Optional.empty()
        ),
        new ConcurrentHashMap<Integer, Optional<BlockingQueue<Packet>>> 
     )
 );

我也嘗試過使用 ConcurrentHashMap:: 和 Integer,可選類型 BlockingQueue 類型 Packet 作為替代完成器,但它也不起作用。 我的 stream 可能有什么問題?

謝謝

您真的不需要 go 圍繞這一點,您可以為此使用收集器的內置實現

ConcurrentMap<Integer, Optional<BlockingQueue<Packet>>> channelMap = contacts.stream()
        .collect(Collectors.toConcurrentMap(Contact::getCid, s -> Optional.empty()));

注意, ConcurrentMap是一個interface ,而ConcurrentHashMap是它的實現之一。 默認的Collectors.toConcurrentMap實現選擇ConcurrentHashMap::new作為上述操作中結果容器的supplier者。

或者Collectors.toConcurrentMap的其他重載可用於將結果顯式轉換為ConcurrentHashMap ,例如:

ConcurrentHashMap<Integer, Optional<BlockingQueue<Packet>>> channelMap = contacts.stream()
        .collect(Collectors.toConcurrentMap(Contact::getCid, s -> Optional.empty(),
                (a, b) -> a, ConcurrentHashMap::new));

暫無
暫無

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

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