簡體   English   中英

在Java流中使用collectors.groupingBy修改返回的Map值類型

[英]Modifying the returned Map value type with collectors.groupingBy in Java stream

我在Entry的類定義之下 -

public class Entry {
    private String key;
    private String Value;
    // getters and setters
    // equals hashcode toString
}

我從數據庫中獲得了Entry對象列表。 我想根據結果的鍵和值對它們進行分組Map應該是Set<value>

我試過並最終得到以下代碼。

Map<String, Set<Entry>> groupedEntries =  
        entryList.findAll()
                 .stream()
                 .collect(Collectors.groupingBy(ek -> ek.getKey().toLowerCase(), Collectors.toSet()));

這段代碼的問題是結果類型是Map<String, Set<Entry>>但是我想成為Map<String, Set<String>>

是否有可能在單一收集中這樣做?

使用mapping收集器:

.collect(Collectors.groupingBy(ek -> ek.getKey().toLowerCase(), 
                  Collectors.mapping(Entry::getValue, Collector.toSet())));

暫無
暫無

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

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