Hi have native sql query which returns List interface class with 3 fields
Trying to find a clean efficient way to do this to reduce to sub-list
Appreciate help
Thanks
SQL query List findResponse();
Response class
public interface Response {
Long getId();
String getSData();
String getSName();
}
The query result converted to json looks as
[
{"id":1,"sData":"UK,FR","sName":"X},
{"id":2,"sData":"UK,FR","sName":"Y"},
{"id":4,"sData":"EU","sName":"X"},
{"id":4,"sData":"Others","sName":"O"}
]
Expected Output For ex for id=4
{
“subData” :
[
{
“sData”: “X”,
“sName”: “EU”
},
{
"sName": "O",
"sData": "Others"
}
]
}
I can create another class if needed
@Data
public class NewResponse {
public Long id;
public List<subData> subDataList;
}
CodePudding user response:
I would start off by grouping to a map:
Map<Long> grouped = responses.stream()
.collect(groupingBy(Response::getId,
mapping(r -> new SubData(r.getSData(), r.getSName()), toList())));
Then you can stream the Map entries to convert them to NewResponse
s:
List<NewResponse> mapped = grouped.entrySet()
.stream()
.map(e -> new NewResponse(e.getKey(), e.getValue()))
.collect(toList());
Feel free to chain the operations if you don't want the extra grouped
variable.