我有
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;
关于java - 使用迭代器从 HashMap 获取(键,值)对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59689394/