【发布时间】:2018-11-16 07:14:18
【问题描述】:
我有一个具有这种结构的对象:
@JsonProperty("id")
private Long codigoCategoria;
@JsonProperty("parentId")
private Long codigoCategoriaPai;
@JsonProperty("name")
private String nomeCategoria;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private ComissaoPadraoEntity comissao;
@JsonProperty("categories")
private List<CategoriaDTO> subCategorias;
你怎么看,它有一个他自己类型的列表,我需要用 Map <Long,List<Long>> 映射这个类别。其中key是codigoCategoria,value必须是一个Long List,子Categorias里面有codigoCategoria。
这是有效载荷结构:
{
"categories": [
{
"id": "1813",
"parentId": null,
"name": "Malas e Mochilas",
"items": 12,
"categories": [
{
"id": "1827",
"parentId": "1813",
"name": "Conjuntos de Malas",
"items": 0,
"categories": [
],
"attributes": null
},
{
"id": "1830",
"parentId": "1813",
"name": "Mochilas",
"items": 4,
"categories": [
{
"id": "1831",
"parentId": "1830",
"name": "Mochila Esportiva",
"items": 0,
"categories": [
],
到目前为止,我已经尝试了许多不同的方法,这是我完成的代码,但甚至无法编译:
private Map<Long, List<Long>> mapATreeofCategories() {
List<CategoriaDTO> categories = getAll();
Map<Long, List<Long>> treeCategories = categories.forEach(categoriaDTO -> {
categories.stream()
.collect(Collectors.toMap(categoriaDTO.getCodigoCategoria(),
categoriaDTO.getSubCategorias().forEach(categoriaDTO1 -> categoriaDTO1.getCodigoCategoria())));
});
return treeCategories;
}
感谢大家的帮助。
【问题讨论】:
-
你得到什么错误?
-
我得到这个错误:Collectors.toMap 不能被应用(长,空)。我试图映射属性,平面地图但也不起作用。
-
请随时edit 将您的问题与错误消息联系起来。问题是
forEach()返回void,因此它不能以您尝试使用它的方式使用。我不熟悉 Stream API,因此无法提供更多帮助。 -
Map<Long, List<Long>> treeCategories = categories.forEach...你知道 forEach 是 Consumer 并且有 void 类型。 -
@GustavoSimõesdeMoraes 你可能只想要
categories.stream() .collect(Collectors.toMap(c -> c.getCodigoCategoria(), v -> v.getSubCategorias() .stream() .map(e -> e.getCodigoCategoria()).collect(Collectors.toList()) );?如果没有,那么您需要编辑您的帖子以明确您的目标。
标签: java dictionary lambda