'How to group in HashMap via stream
I have the following DTO and projection interface:
@Data
public class StatusDTO{
private UUID productUuid;
private boolean disabled;
// constructors
}
I fill these fields in my repository:
public interface ProductDTO {
UUID getProductUuid();
UUID getProductCategoryUuid();
boolean getDisabled();
}
However, when I try to create a mapping by grouping getProductCategoryUuid and its corresponding List<StatusDTO>, I get error in the new StatusDTO(...) part as "UUID is not a functional interface" and "boolean is not a functional interface".
So, how can I build a map using ProductDTO::getProductCategoryUuid - List<StatusDTO> pairs?
Do I need LinkedHashMap as I tried below?
final Map<UUID, List<StatusDTO>> map = demoService.findAll().stream()
.collect(groupingBy(ProductDTO::getProductCategoryUuid, LinkedHashMap::new,
Collectors.mapping(new StatusDTO(
ProductDTO::getProductUuid,
ProductDTO::getDisabled)
), Collectors.toList()));
Update: The foolowing approach seems to work, but I am not sure if it is a proper way. I use LinkedHashMap to maintain order. Any idea?
final Map<UUID, List<StatusDTO>> map = demoService.findAll().stream()
.collect(groupingBy(
ProductDTO::getProductCategoryUuid, LinkedHashMap::new,
Collectors.mapping(p -> new StatusDTO(
p.getProductUuid(),
p.getDisabled()),
Collectors.toList())));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
