文
章
目
录
章
目
录
在Java中,子Map是给定Map的一部分,位于特定范围的键之间。本文将讨论从Map中获取子Map的不同技术。
1.使用Map.keySet().retainAll()
retainAll()方法从Map中移除不包含在指定列表中的所有键。请注意,retainAll()会从原始集合中删除条目,因此如果不想修改原始Map,应在Map的新副本上执行此操作。
Map<String, String> map = new HashMap<>();
map.put("key1", "Value1");
map.put("key2", "Value2");
map.put("key3", "Value3");
List<String> keysToRetain = List.of("key1", "key2");
map.keySet().retainAll(keysToRetain);
System.out.println(map); //{key1=Value1, key2=Value2}
2.使用TreeMap的submap()、headMap()和tailMap()
TreeMap类按键按照自然顺序或使用自定义排序的提供者Comparator来存储键值对。TreeMap允许使用以下方法获取子Map。
- subMap(fromKey, toKey): 返回一个视图,其键范围从fromKey(包括)到toKey(不包括)。
- headMap(toKey): 返回一个视图,其键严格小于toKey。
- tailMap(fromKey): 返回一个视图,其键大于或等于fromKey。
这些方法还可以与SortedMap和NavigableMap的其他Map实现一起使用。
TreeMap<String, String> treeMap = new TreeMap<>();
treeMap.put("key1", "Value1");
treeMap.put("key2", "Value2");
treeMap.put("key3", "Value3");
SortedMap<String, String> subMap = treeMap.subMap("key2", "key3"); //{key2=Value2}
SortedMap<String, String> headMap = treeMap.headMap("key2"); //{key1=Value1}
SortedMap<String, String> tailMap = treeMap.tailMap("key2"); //{key2=Value2, key3=Value3}
请注意,以下每种方法都返回一个由原始Map支持的Map,因此子Map中的更改会反映在原始Map中,反之亦然。
subMap.put("key2", "NEW_VALUE_2");
System.out.println(subMap); //{key2=NEW_VALUE_2}
System.out.println(treeMap); //{key1=Value1, key2=NEW_VALUE_2, key3=Value3}
同样,在原始Map中添加新条目也会更改Map视图。例如,在原始Map中添加新的键值对key4:value4将反映在所有子Map视图中。
treeMap.put("key4", "value4");
System.out.println(tailMap); //{key2=NEW_VALUE_2, key3=Value3, key4=value4}
System.out.println(treeMap); //{key1=Value1, key2=NEW_VALUE_2, key3=Value3, key4=value4}
3.使用Stream API
Stream是来自源的数据集合或序列。我们可以使用Stream API来遍历、筛选和收集所需的键值对到一个新的Map中。新Map不由原始Map支持,因此我们可以在两个Map中更改条目而不会影响另一个Map。
Map<Integer, String> hashmap = new HashMap<>();
hashmap.put(1, "Value1");
hashmap.put(2, "Value2");
hashmap.put(3, "Value3");
List<Integer> keysList = Arrays.asList(1, 2);
Map<Integer, String> subHashmap = hashmap.entrySet()
.stream()
.filter(x -> keysList.contains(x.getKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(subHashmap); //{1=Value1, 2=Value2}
4.使用Guava的Maps类
Guava是一组提供各种实用方法的标准库。它的Maps类提供了以下用于从指定的Map中过滤键或值以获取新Map的实用方法。
- Maps.filterKeys(unfilteredMap, keyPredicate)
- Maps.filterValues(unfilteredMap, valuePredicate)
- Maps.filterEntries(unfilteredMap, entryPredicate)
在每种方法中,我们传递原始Map和匹配要在子Map中填充的键、值或条目的Predicate。
Map<Integer, String> hashmap = new HashMap<>();
hashmap.put(1, "Value1");
hashmap.put(2, "Value2");
hashmap.put(3, "Value3");
List<Integer> keysList = Arrays.asList(1, 2);
Map<Integer, String> subMap = Maps.filterKeys(hashmap, Predicates.in(keysList));
System.out.print(subMap); //{1=Value1, 2=Value2}
5.结论
在本Java教程中,我们学习了使用Map API和Stream API以及Guava的filter()方法从指定的Map中获取子Map的不同技术。要获得与原始Map无关的子Map,我们必须遍历Map条目并从所选条目创建新的Map。