biniam:
iは物体の2Dアレイ(有するObject [][]
データベースを照会から返されます)。私は今、グループ化した後、API呼び出しで返される可能性がオブジェクトにマッピングします。
ここに私の2Dオブジェクトの配列です。
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
}
]
}
]
}
]
ETO:
あなたが使用する必要があるように見えますCollectors.collectingAndThen
。
(あなたのクラスはコンストラクタ&ゲッターを持っていると仮定すると)最初の抽出を作成します。
// 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));