gpt4 book ai didi

java - Java中如何合并两个对象的属性? (用户定义类的属性和Map的键值)

转载 作者:行者123 更新时间:2023-12-02 03:35:08 30 4
gpt4 key购买 nike

我正在开发 Spring Boot 应用程序,并且有两个对象,一个是自定义类的列表,另一个是字符串键和字符串值的映射。例如。

DTO object with fixed fields fieldA,fieldB,fieldc. 

[{"fieldA": "lookupval1","fieldB": "val2","fieldc":"val3"},
{"fieldA": "lookupval1","fieldB": "val5","fieldc":"val6"}
{"fieldA": "lookupval2","fieldB": "val8","fieldc":"val9"}]

另外请注意,该字段 A 对于前两个对象具有重复的值

然后我有 map Map<String,Map<String,String> 的 map 像下面这样

{
lookupval1= {fieldA:"lookupval1",fieldD:"xxx",.............},
lookupval2= {fieldA:"lookupval2",fieldD:"yyy",.............}.
.
.
.
}

我想要的是,我想将列表中每个项目中的字段与Map中的字段组合起来,我可以通过获取fieldA的查找值来找到Map中相应的键。

字段A:lookupval1

然后我想将该响应发送到 REST 客户端,执行此操作的有效方法和数据结构是什么?

预期结果:

[
{"fieldA": "lookupval1","fieldB": "val2","fieldc":"val3",fieldD:"xxx"},
{"fieldA": "lookupval1","fieldB": "val2","fieldc":"val3",fieldD:"xxx"}
{"fieldA": "lookupval2","fieldB": "val8","fieldc":"val9",fieldD:"yyy"}]
]

更新:

下面是DTO对象的结构和Map的具体类型。

class DTO {
int id;
String name;
String desc;
}

List<DTO> dtoList = getDTOList(); // returns list of DTO object

Map<String,Map<String,String> mapCollection
= getMapCollection(); // return String, Map<String,String> pairs
  • 这里mapCollection中的key总是等于DTO和DTO列表的id将会有重复的值。

我已经按照我的方式发布了答案,但正在寻找更好的替代方案来减少计算。

最佳答案

List<DTO> dtoList = getDTOList(); // returns list of DTO object

Map<String,Map<String,String> mapCollection
= getMapCollection(); // return String, Map<String,String> pairs
List<Map<String,String>> result = new HashMap<>();

// iterate over dto list
for(DTO singleDTO : dtoList) {
Map<String,String> singleResult = new HashMap<>();

// Add all fields in map
singleResult.put("id",singleDTO.getId());
singleResult.put("name",singleDTO.getName());
singleResult.put("desc",singleDTO.getDesc());

// fetch single map by id lookup
Map<String,Strig> singleMap = mapCollection.get(singleDTO.getId());
// fetch all entries from map
Set<Map.Entry<String,String>> entrySet = singleMap.entrySet();
// add them in hashmap
for(Map.Entry<String,String> singleEntry : entrySet) {
singleResult.put(singleEntry.getKey(),singleEntry.getValue());

Add map in the list
result.add(singleEntry);
}}

//result

[
{
"id":"1", "name":"abc", "desc":"some desc abc", "ID":"1", "mapField1":"field1 value", "mapField2":"field1 value"
},
{
"id":"1", "name":"xyz", "desc":"some desc xyz", "ID":"1", "mapField1":"field1 value", "mapField2":"field1 value"
},
{
"id":"2", "name":"pqr", "desc":"some desc pqr", "ID":"2", "mapField1":"field1 value 2", "mapField2":"field1 value2"
}
]

关于java - Java中如何合并两个对象的属性? (用户定义类的属性和Map的键值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56865658/

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