通过键在hashmap中聚合值

Sal*_*lil 0 java collections

考虑一个简单的HashMap<Integer,Integer>.如何获取存储的所有值,这些键是5的倍数?我对工作JavaCollections现在有一段时间了,但突然我无言以对.

任何帮助将受到高度赞赏.

问候,

萨里尔

Lou*_*man 6

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)