考虑一个简单的HashMap<Integer,Integer>.如何获取存储的所有值,这些键是5的倍数?我对工作Java和Collections现在有一段时间了,但突然我无言以对.
任何帮助将受到高度赞赏.
问候,
萨里尔
List<Integer> values = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getKey() % 5 == 0) {
values.add(entry.getValue());
}
}
Run Code Online (Sandbox Code Playgroud)
FWIW,类似的Java 8方法可能看起来像
map.entrySet().stream()
.filter(entry -> entry.getKey() % 5 == 0)
.map(Entry<Integer, Integer>::getValue)
.collect(toList());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
942 次 |
| 最近记录: |