我正在做一个项目,在该项目中,下面的方法将包含一个“字符串和对象的映射”。并假设其中是否data Map
包含这样的内容-
a = p
b = q
c = r
d = s
e = t
f = u
g = v
h = w
i = x
a, b, c, d, e, f, g
钥匙在哪里p, q, r, s, t, u, v
,在上面的地图中是否有相应的值。
下面是我的方法-
private void dataCheck(Map<String, Object> data) {
}
现在,我在另一个String和String映射中有另一个这样的静态映射-
public static final Map<String, String> STATIC_MAPPING = Collections.unmodifiableMap(new LinkedHashMap<String, String>() {{
put("a","hello");
put("b","world");
put("c","titan");
put("d","david");
put("e","elephant");
put("f","fire");
put("g","gel");
}});
这里keya
的hello
值是,keyb
的world
值c
是titan
,key的值与其他key值对相同。
现在,如上所述,在下面的方法中,我将在Map中获取包含上面所示数据的值-
private void dataCheck(Map<String, Object> data) {
// how to get extract the value of the key from the
// STATIC_MAPPING map corresponding to data map key.
// print out a new map here with latest mappings
}
现在,就像数据映射将具有一样a = p
,它将被替换为,hello = p
因为a
它映射到hello
STATIC_MAPPING中所示的位置,并且与其他字段相同。我如何有效地做到这一点?
并假设如果数据映射中的键没有任何映射,那么我们将保持原样。
更新:-
所以我的新地图应该有这样的数据-
hello = p
world = q
titan = r
david = s
elephant = t
fire = u
gel = v
h = w
i = x
由于没有键的映射h
,i
所以我会保持原样..
for (Map.Entry<String, Object> entry : data.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
String staticMappingValue = (String) STATIC_MAPPING.get(key);
if (staticMappingValue != null) {
newMap.put(staticMappingValue, value);
} else {
newMap.put(key, value);
}
}
这样newMap
:
["hello":"p", "world":"q", etc..., "h":"w"]
编辑:遵循Antoine Wils的建议并减少了对地图的访问,因为问题突出了效率。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句