为了账号安全,请及时绑定邮箱和手机立即绑定

Java 8 按键分组映射

Java 8 按键分组映射

慕莱坞森 2021-08-04 09:31:32
我想按键对地图对象进行分组。我尝试使用此代码,但出现编译错误:Non-static method cannot be referenced from a static context我的代码:Map<String, List<A>> getAMap() {            return Arrays.stream(SomeArray.values())            .map(map -> createObject())            .collect(Collectors.groupingBy(Map.Entry::getKey,                   Collectors.mapping(Map.Entry::getValue, Collectors.toList())));}private Map<String, A> createObject()     final A a = new A(some attributes);    Map<String, A> map = new LinkedHashMap<>();    map.put(some key, a);    .... // add another values.     return map;}我需要类似的东西{"a", {a1, a2, a3},"b", {a4, a5, a6},}
查看完整描述

1 回答

?
料青山看我应如是

TA贡献1772条经验 获得超8个赞

看起来您的代码在某些级别上是错误的,并且该错误消息并不是究竟发生了什么。

例如createObject()返回 aMap所以你得到 a Stream<Map<...>>,所以显然.collect(Collectors.groupingBy(Map.Entry::getKey...行不通。您需要稍微更改代码才能使其正常工作:

Arrays.stream(someArray)
            .flatMap(map -> createObject().entrySet().stream())
            .collect(Collectors.groupingBy(Entry::getKey,
                    Collectors.mapping(Entry::getValue, Collectors.toList())));


查看完整回答
反对 回复 2021-08-04
  • 1 回答
  • 0 关注
  • 213 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信