gpt4 book ai didi

Java 8 : Group Object array to Map to return as JSON

转载 作者:搜寻专家 更新时间:2023-11-01 03:31:09 25 4
gpt4 key购买 nike

我有一个从查询数据库返回的对象二维数组 (Object [][])。我现在想将它映射到分组后可以在 API 调用中返回的对象。

这是我的二维对象数组。

Object [][] dbResult = 
{
{1, "a", 9, "Content1", "format1", false, true},
{1, "a", 9, "Content1", "format2", true, false},
{2, "b", 8, "Content2", "format3", true, false},
{2, "b", 8, "Content2", "format4", false, false},
{3, "c", 7, "Content3", "format5", true, true},
{4, "d", 8, "Content2", "format6", false, true},
{4, "d", 6, "Content3", "format7", true, true},
{4, "d", 5, "Content4", "format8", false, false},
{5, "e", 4, "Content5", "format9", false, true},
{6, "f", 3, "Content6", "format10", true, false}
};

Here is the legend/key for the index.
[ID, Name, AnotherID, AnotherName, Format, Boolean, Boolean]

我要回去

List<IdName> idsNames;

每个类都应该像这样映射。

class IdName {
String id;
String name;
List<Another> anotherNameList;
}

class Another {
String anotherId;
String anotherName;
List<Format> formatList;
}

class Format {
String format;
Boolean isEnabled;
Boolean isManaged;
}

我尝试使用 Java 8 的 groupingBy 但我无法达到我想要的状态。

示例预期结果:

[
{
"id": 1,
"name": "a",
"another": [
{
"anotherId": 9,
"anotherName": "Content1",
"format": [
{
"format": "format1",
"isEnabled": true,
"isManaged": false
},
{
"format": "format2",
"isEnabled": true,
"isManaged": false
}
]
}
]
}
]

最佳答案

看起来你应该使用 Collectors.collectingAndThen

首先创建提取器(假设您的类有构造函数和 getter):

// The cast types are just an example. You can Cast/convert the array values to any type you want

IdName extractIdName(Object[] row) {
return new IdName((String) row[0], (String) row[1], null);
}

Another extractAnother(Object[] row) {
return new Another((String) row[2], (String) row[3], null);
}

Format extractFormat(Object[] row) {
return new Format((String) row[4], (boolean) row[5], (boolean) row[6]);
}

然后您将需要合并功能:

List<Another> setFormats(Map<Another, List<Format>> map) {
return map.entrySet()
.stream()
.map(e -> {
e.getKey().setFormatList(e.getValue());
return e.getKey();
})
.collect(toList());
}

List<IdName> setAnothers(Map<IdName, List<Another>> map) {
return map.entrySet()
.stream()
.map(entry -> {
entry.getKey().setAnotherNameList(entry.getValue());
return entry.getKey();
})
.collect(toList());
}

最后这会成功:

// Converting Object[][] to List<IdName>
List<IdName> list =
Arrays.stream(dbResult)
.collect(
collectingAndThen(
groupingBy(this::extractIdName,
collectingAndThen(
groupingBy(this::extractAnother,
mapping(this::extractFormat, toList())),
this::setFormats
)),
this::setAnothers));

关于Java 8 : Group Object array to Map to return as JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54225969/

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