【发布时间】:2021-12-22 19:09:00
【问题描述】:
我这里有两张地图:
地图A
Map<String, String> mapA = new HashMap<>();
mapA.put("aaa|111|osdf", "value1");
mapA.put("bbb|222|dfsf", "value2");
...
地图B
Map<String, String> mapB = new HashMap<>();
mapB.put("aaa", "valueM");
mapB.put("bbb", "valueN");
...
如果mapB中的键是mapA中键的子字符串,现在我想获取mapA中的键,就像:
mapB.forEach((key, value) -> {
if (mapA.containsKey(key)) {
// This is not what I want, because key in mapB is substring of key in mapA.
// nested loop is not suggested here.
}
})
输出
aaa|111|osdf
bbb|222|dfsf
如何获取 mapA 中的键,因为 mapB 中的键是 mapA 中键的子字符串?
【问题讨论】:
-
根据您的示例,mapA 中的键的第一部分,如“aaa”或“bbb”(第一个“|”之前的部分)可以在 mapB 中作为键。这个假设正确吗?
-
正确,但出于某种原因,应该遍历mapB
-
对于 mapA,我们可以使用 Map
代替 Map 吗?如果是,那么在自定义类中我们可以在第一个管道之前修改 equals 和 hashCode 以使用“字符串”?
标签: java search hashmap substring