项目场景:
Java8 Map使用stream模糊匹配key,
filter过滤出符合条件的数据。
解决方案:
public static void main(String[] args) {
Map<String, String> testMap = new HashMap<>();
testMap.put("1-1","测试1");
testMap.put("2-1","测试2");
testMap.put("3-1","测试3");
Map<String, String> filterMap = testMap.entrySet().stream()
.filter(t -> t.getKey().matches("2"+"-.*"))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue)
);
System.out.println(filterMap);
String firstValue = map.values().stream().findFirst().orElse(null);
System.out.println("第一个值为:" + firstValue);
}