gpt4 book ai didi

列表中 map 的Java流更改键

转载 作者:行者123 更新时间:2023-12-04 03:03:18 26 4
gpt4 key购买 nike

是否可以使用 java 流来更改列表中 map 的键,即给出 map 的原始列表是:

List<Map<String, String>> list = new ArrayList<Map<String, String>>() {{
add(new HashMap<String, String>() {{
put("id", "1");
put("display", "foo");
}});
add(new HashMap<String, String>() {{
put("id", "2");
put("display", "bar");
}});
}};

System.out.println(list.toString());

来自上面的列表(用于演示的输出)

[{display=foo, id=1}, {display=bar, id=2}]

到 map 列表:

[{sample=foo, sample_id=1}, {sample=bar, sample_id=2}]

基本上,将键“id”更改为“sample_id”,将“display”更改为“sample”。

最佳答案

这会起作用,

    List<Map<String, String>> list2 = list.stream().map(e -> {
Map<String, String> map = new HashMap<>();
for (Map.Entry x : e.entrySet()) {
if (x.getKey().equals("id")) {
map.put("sample_id", (String) x.getValue());
} else if (x.getKey().equals("display")) {
map.put("sample", (String) x.getValue());
} else {
map.put((String) x.getKey(), (String) x.getValue());
}
}

return map;
}).collect(Collectors.toList());

稍微优雅一些​​,

    List<Map<String, String>> list3 = list.stream().map(
e -> e.entrySet().stream().collect(Collectors.toMap(
x -> {
if (x.getKey().equals("id")) {
return "sample_id";
} else if (x.getKey().equals("display")) {
return "sample";
} else {
return x.getKey();
}
},
Map.Entry::getValue))).collect(Collectors.toList());

关于列表中 map 的Java流更改键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46967382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com