Java 8流:按列表分组到平面地图

时间:2017-10-31 07:56:25

标签: java java-8 java-stream

我有以下情况。 (伪代码)

int totalLength = 0;
        List<GwtGroup> gwtGroupList = new ArrayList<GwtGroup>();
        try {
            KapuaLocator locator = KapuaLocator.getInstance();
            GroupService groupService = locator.getService(GroupService.class);
            UserService userService = locator.getService(UserService.class);
            GroupQuery groupQuery = GwtKapuaAuthorizationModelConverter.convertGroupQuery(loadConfig,
                    gwtGroupQuery);
            GroupListResult groups = groupService.query(groupQuery);
            if (!groups.isEmpty()) {
                if (groups.getSize() >= loadConfig.getLimit()) {
                    totalLength = Long.valueOf(groupService.count(groupQuery)).intValue();

                } else {
                    totalLength = groups.getSize();
                }
                for (Group g : groups.getItems()) {
                    gwtGroupList.add(KapuaGwtAuthorizationModelConverter.convertGroup(g));
                    for (GwtGroup gwtGroup : gwtGroupList) {
                        User user = userService.find(g.getScopeId(), g.getCreatedBy());
                        if (user != null) {
                            gwtGroup.setUserName(user.getDisplayName());
                        }
                }
            }
            }
        } catch (Exception e) {
            KapuaExceptionHandler.handle(e);
        }
        return new BasePagingLoadResult<GwtGroup>(gwtGroupList, loadConfig.getOffset(),
                totalLength);
    }

我想知道如何转换List os As - &gt; Bs地图

class A {
  id;
  List<B> bs;
}

class B {}

1 个答案:

答案 0 :(得分:3)

好像你想要这样的时间:

 Map<Integer, List<B>> bs = as.stream()
        .collect(Collectors.toMap(A::getId, A::getBs));