我的输入中有一个总共13个HashMap的列表。每个HashMap只有两个键“ fieldName”和“ accessibilityType”以及相应的值:
"fieldAccessibility": [
{
"fieldName": "firstName",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "lastName",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "avatarUrl",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "username",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "birthDate",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "phoneNumbers",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "email",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "language",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "externalId",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "externalCode",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "punchBadgeId",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "minor",
"accessibilityType": "EDITABLE"
},
{
"fieldName": "seniorityDate",
"accessibilityType": "EDITABLE"
}
]
我正在尝试遍历此过程,并将“ accessibilityType”的值更改为“ READ”,其中“ fieldName”是“ birthDate”。有人可以说一下这样做的有效方法。到目前为止,这是我尝试读取和打印每个键值对的尝试:
final List<HashMap<String, String>> list = some code to get the input;
for (HashMap<String, String> m : list)
{
for (HashMap.Entry<String, String> e : m.entrySet())
{
String key = e.getKey();
String value = e.getValue();
System.out.println("SEE HERE TEST " + key + " = " + value);
}}
答案 0 :(得分:1)
从JDK-8开始,可以使用forEach
按照以下步骤进行操作:
list.forEach(map -> {
String fieldName = map.get("fieldName");
if("birthDate".equals(fieldName)) map.put("accessibilityType", "READ");
});
答案 1 :(得分:1)
您可以这样做
List<Map<String, String>> updatedMaps = list.stream()
.map(m -> m.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> m.containsValue("birthDate") && e.getKey().equals("accessibilityType") ? "READ" : e.getValue())))
.collect(Collectors.toList());
浏览每张地图,同时将其映射到新地图。键保持不变,只有值可以更改。如果您的地图包含键birthDate
,并且当前条目的键是accessibilityType
,则将READ作为该地图条目的新值。否则,请保留现有值。最后,将所有新地图收集到结果容器中。