I have 2 classes:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class FirstDTO {
private Long id;
@Builder.Default
private List<SecondDTO> secondDTOs = Lists.newArrayList();
}
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SecondDTO {
private Long id;
private String code;
}
My controller returns List of FirstDTO:
ResponseEntity<List<FirstDTO>> add(List<MySampleDTO> dtoList);
The controller can get a List what will produces multiple FirstDTO as response. In FirstDTO I include the id
of it and a List<SecondDTO>
. The problem is that it can happen that the data will be redundant:
[
{
"id": 1,
"secondDTO": [
{
"id": 200,
"code": "MY_200_TEST_CODE"
}
]
},
{
"id": 1,
"secondDTO": [
{
"id": 200,
"code": "MY_200_TEST_CODE"
},
{
"id": 300,
"code": "MY_300_TEST_CODE"
}
]
}
]
As you can see the second object of the json would be enough as response because it contains the first object. So I would like to use java 8 streams (or any other method) that will transform the list I showed earlier, to this:
[
{
"id": 1,
"secondDTO": [
{
"id": 200,
"code": "MY_200_TEST_CODE"
},
{
"id": 300,
"code": "MY_300_TEST_CODE"
}
]
}
]
So basically I need a method that groups FirstDTOs based on it's id
and then save only FirstDTO with given id
that has the longest list of SecondDTOs
Thanks in advance.