pom文件:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
代码:
package com.example.core.utils.collections;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class FilterMapByKeyTest {
public static void main(String[] args) {
// 过滤生成map<3的数据
Map<Integer, String> map = new HashMap<>();
map.put(1,"a");
map.put(2,"b");
map.put(3,"c");
map.put(4,"d");
// 方法一:Java原生Map遍历过滤
Map<Integer, String> newMap = new HashMap<>();
Set<Map.Entry<Integer, String>> entries = map.entrySet();
for (Map.Entry<Integer, String> entry : entries) {
if (entry.getKey() < 3) {
newMap.put(entry.getKey(),entry.getValue());
}
}
System.out.println(newMap);
// 方法二:Java8新特性 Lambda表达式过滤
Map<Integer, String> newMap2 = map.entrySet().stream().filter(m -> m.getKey() < 3).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(newMap2);
// 方法三:google.guava 方法
Map<Integer, String> newMap3 = Maps.filterKeys(map, m -> m < 3);
System.out.println(newMap3);
}
}
标签:Map,Java,map,util,java,key,put,import
From: https://www.cnblogs.com/wuzimeimei/p/17548229.html