获取 EntrySet
, 然后正常使用 stream
的 filter
过滤 Entry
, 最后再转为 Map
即可
/**
* 对 map 过滤
* filter
*/
@Test
public void testMapFilter() {
Map<Integer, String> map = new HashMap<>();
map.put(100, "e");
map.put(5, "a");
// 先转为 entrySet 再 stream filter (true 为留下的, false 为排除掉的)
// 最后 collectors.toMap e.getKey e.getValue
map = map.entrySet()
.stream()
.filter(entry -> {
String value = entry.getValue();
return value.contains("e");
}).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()));
System.out.println(map);
}