【发布时间】:2020-06-25 08:49:35
【问题描述】:
我有一个地图,它可以有键:A, B, C, D, E, F 或它的子集
其中,A, B, C and D是一组按相同顺序属于某个层次结构的字符串:A -> B -> C -> D
如果地图包含有效的层次结构,我需要检查HashMap。以哪个顺序映射存储数据无关紧要。我不关心订单,也不会检查地图内的订单。
如果地图包含其中任何一个,则将其视为有效层次结构:
A or
A, B or // A and B can be in any order
A, B, E or // as E is not in the group, so doesn't matter
A, B, C or // these can be in any order in map.
A, B, C, D or
如果map有A, B, and D但没有C,则视为无效。
我可以添加多个if else 检查,但这会使代码混乱。有什么优雅的方式来做这个检查吗?
编辑: 我已经实现了以下逻辑:
// order contains strings in order: { A, B, C, D}
private boolean isHierarchyComplete(Map<String, Object> map, String[] order) {
// lastIndexFound, this will give the last index of string found in hierarchy that is continous and breaks out once the path is broken
int lastIndexFound = -1;
for (String str : order) {
if (map.containsKey(str)) {
lastIndexFound++;
} else {
break;
}
}
// if nothing found from path
if (lastIndexFound == -1) {
return false;
}
// if all found from path
if (lastIndexFound == order.length - 1) {
return true;
}
// now check after lastIndexFound if there are any values from hierarchy,
// if present return false
for (int index = lastIndexFound + 1; index < order.length; index++) {
if (map.containsKey(order[index])) {
return false;
}
}
return true;
}
【问题讨论】:
-
请注意,常规 Java
HashMap的键是 not 有序的,这意味着如果键A、B和C存在,则迭代键可以以任何顺序返回它们。 -
这样的?
if (!map.contains("A") || !map.contains("B") || !map.contains("C") || !map.contains("D")) invalid else valid -
@TimBiegeleisen 是的地图不保留顺序。我不在乎什么地图顺序地图保存数据。我想检查我提到的字符串组中是否存在 Map 中的所有值。
-
连我都不明白投反对票的原因?因为我觉得这个问题很清楚。点赞
-
如果您需要支持有限的、固定的和已知的密钥集,请考虑将密钥包装到
enum并使用EnumMap。它将防止您使用不正确的密钥 - 然后密钥类型将确保正确性。