从List、stream和Java 8创建具有嵌套属性的嵌套映射。

7

我提出了这个问题:使用forEach和Java 8创建嵌套列表(List of List)的流

class EntityCompositeId {
    private Long firstId;
    private Long secondId;
    // getter & setter...
}

class EntityComposite {
    private EntityCompositeId id;
    private String first;
    private String second;
    // getter & setter...
}

List<EntityComposite> listEntityComposite = ....
Supose this content

1, 1, "firstA", "secondBirdOne"
1, 2, "firstA", "secondBirdTwo"
1, 3, "firstA", "secondBirdThree"

2, 1, "firstB", "secondCatOne"
2, 2, "firstB", "secondCatTwo"
2, 3, "firstB", "secondCatThree"

3, 1, "firstC", "secondDogOne"
3, 2, "firstC", "secondDogTwo"
3, 3, "firstC", "secondDogThree"

Map<Long, Map<Long, String>> listOfLists = new HashMap<>();

现在我想使用流来填充,例如:
 1 -> {1 ->"secondBirdOne", 2 -> "secondBirdTwo", 3 -> "secondBirdThree"}
 2 -> {1 ->"secondCatOne", 2 -> "secondCatTwo", 3 -> "secondCatThree"}
 3 -> {1 ->"secondDogOne", 2 -> "secondDogTwo", 3 -> "secondDogThree"}

我的代码没有起作用,代码如下:

    Map<Long, Map<Long, String>> listaMunDepa = listEntityComposite.stream()
        .collect(Collectors.groupingBy(
            e -> e.getId().getFirstId(),
            Collectors.toMap(f -> f.getId().getSecondId(), Function.identity()))
    );

第二次尝试

    Map<Long, Map<Long, String>> listaMunDepa = listEntityComposite.stream()
        .collect(Collectors.groupingBy(
            e -> e.getId().getFirstId(),
            Collectors.groupingBy(EntityComposite::getId::getSecondId, EntityComposite::getSecond)) // How change this line
    );
1个回答

5

您离正确答案很近了,不要传递Function.identity,而是应该传递EntityComposite::getSecond

listEntityComposite.stream()
           .collect(groupingBy(e -> e.getId().getFirstId(),
                  toMap(f -> f.getId().getSecondId(), EntityComposite::getSecond)));

因为你提供了Function.identity,结果是Map<Long, Map<Long, EntityComposite>>,所以如上所示,你只需要从提供给toMapvalueMapper函数中提取getSecondId,从而得到一个Map<Long, Map<Long, String>>

抱歉,关于 https://stackoverflow.com/questions/61844376 的情况怎么样,谢谢。 - joseluisbz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接