簡體   English   中英

使用迭代器從 HashMap 中獲取(鍵,值)對

[英]Getting (key, value) pairs from a HashMap using an iterator

我有

private Map<K,Collection<V>> map = new HashMap<>();

我想返回值

public Iterable<Map.Entry<K, V>> allValues() {
}

我怎么能將值作為 Iterable 返回?

您可以按如下方式使用流:

Iterable<Map.Entry<K, V>> iterable = map.entrySet().stream()
    .flatMap(e -> e.getValue().stream().map(v-> entry(e.getKey(), v)))
    .collect(toList());

這假設 Java 9 或更高版本(對於Map.entry )和以下靜態導入:

import static java.util.Map.entry;
import static java.util.stream.Collectors.toList;

暫無
暫無

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

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