Example usage for java.util.stream Collectors groupingBy

List of usage examples for java.util.stream Collectors groupingBy

Introduction

In this page you can find the example usage for java.util.stream Collectors groupingBy.

Prototype

public static <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier) 

Source Link

Document

Returns a Collector implementing a "group by" operation on input elements of type T , grouping elements according to a classification function, and returning the results in a Map .

Usage

From source file:org.drools.devguide.phreakinspector.model.PhreakInspector.java

private InputStream generateGraphViz(Map<Integer, Node> nodes) throws IOException {

    String template = IOUtils.toString(PhreakInspector.class.getResourceAsStream("/templates/viz.template"));
    ST st = new ST(template, '$', '$');
    st.add("items", nodes.values());

    Map<String, List<Node>> itemsByGroup = nodes.values().stream()
            .collect(Collectors.groupingBy(n -> n.getType().getGroup()));
    st.add("itemsByGroup", itemsByGroup);

    return new ByteArrayInputStream(st.render().getBytes());

}

From source file:org.eclipse.collections.impl.jmh.AnagramBagTest.java

@Benchmark
public void serial_lazy_streams_ec() {
    Map<Alphagram, List<String>> groupBy = this.ecWords.stream().collect(Collectors.groupingBy(Alphagram::new));
    groupBy.entrySet().stream().map(Map.Entry::getValue).filter(list -> list.size() >= SIZE_THRESHOLD)
            .sorted(Comparator.<List<String>>comparingInt(List::size).reversed())
            .map(list -> list.size() + ": " + list).forEach(e -> Assert.assertFalse(e.isEmpty()));
}

From source file:org.eclipse.collections.impl.jmh.AnagramBagTest.java

@Benchmark
public void parallel_lazy_streams_ec() {
    Map<Alphagram, List<String>> groupBy = this.ecWords.parallelStream()
            .collect(Collectors.groupingBy(Alphagram::new));
    groupBy.entrySet().parallelStream().map(Map.Entry::getValue).filter(list -> list.size() >= SIZE_THRESHOLD)
            .sorted(Comparator.<List<String>>comparingInt(List::size).reversed())
            .map(list -> list.size() + ": " + list).forEach(e -> Assert.assertFalse(e.isEmpty()));
}

From source file:org.eclipse.hawkbit.repository.jpa.JpaRolloutManagement.java

private Map<Long, List<TotalTargetCountActionStatus>> getStatusCountItemForRollout(final List<Long> rollouts) {
    if (rollouts.isEmpty()) {
        return null;
    }/*from   w w w.  j av a  2 s .  c om*/

    final Map<Long, List<TotalTargetCountActionStatus>> fromCache = rolloutStatusCache
            .getRolloutStatus(rollouts);

    final List<Long> rolloutIds = rollouts.stream().filter(id -> !fromCache.containsKey(id))
            .collect(Collectors.toList());

    if (!rolloutIds.isEmpty()) {
        final List<TotalTargetCountActionStatus> resultList = actionRepository
                .getStatusCountByRolloutId(rolloutIds);
        final Map<Long, List<TotalTargetCountActionStatus>> fromDb = resultList.stream()
                .collect(Collectors.groupingBy(TotalTargetCountActionStatus::getId));

        rolloutStatusCache.putRolloutStatus(fromDb);

        fromCache.putAll(fromDb);
    }

    return fromCache;
}

From source file:org.eclipse.winery.repository.rest.resources.AbstractComponentsResource.java

/**
 * Used by org.eclipse.winery.repository.repository.client and by the artifactcreationdialog.tag. Especially the
 * "name" field is used there at the UI//from w  w w . j a  v  a  2  s . com
 *
 * @param grouped if given, the JSON output is grouped by namespace
 * @return A list of all ids of all instances of this component type. <br /> Format: <code>[({"namespace":
 * "[namespace]", "id": "[id]"},)* ]</code>. <br /><br /> If grouped is set, the list will be grouped by namespace.
 * <br /> <code>[{"id": "[namsepace encoded]", "test": "[namespace decoded]", "children":[{"id": "[qName]", "text":
 * "[id]"}]}]</code>
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public String getListOfAllIds(@QueryParam("grouped") String grouped) {
    Class<? extends TOSCAComponentId> idClass = RestUtils
            .getComponentIdClassForComponentContainer(this.getClass());
    boolean supportsNameAttribute = Util.instanceSupportsNameAttribute(idClass);
    SortedSet<? extends TOSCAComponentId> allTOSCAcomponentIds = RepositoryFactory.getRepository()
            .getAllTOSCAComponentIds(idClass);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter sw = new StringWriter();
    try {
        JsonGenerator jg = jsonFactory.createGenerator(sw);
        // We produce org.eclipse.winery.repository.client.WineryRepositoryClient.NamespaceAndId by hand here
        // Refactoring could move this class to common and fill it here
        if (grouped == null) {
            jg.writeStartArray();
            for (TOSCAComponentId id : allTOSCAcomponentIds) {
                jg.writeStartObject();
                jg.writeStringField("namespace", id.getNamespace().getDecoded());
                jg.writeStringField("id", id.getXmlId().getDecoded());
                if (supportsNameAttribute) {
                    AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                            .getComponentInstaceResource(id);
                    String name = ((IHasName) componentInstaceResource).getName();
                    jg.writeStringField("name", name);
                } else {
                    // used for winery-qNameSelector to avoid an if there
                    jg.writeStringField("name", id.getXmlId().getDecoded());
                }
                jg.writeStringField("qName", id.getQName().toString());
                jg.writeEndObject();
            }
            jg.writeEndArray();
        } else {
            jg.writeStartArray();
            Map<Namespace, ? extends List<? extends TOSCAComponentId>> groupedIds = allTOSCAcomponentIds
                    .stream().collect(Collectors.groupingBy(id -> id.getNamespace()));
            groupedIds.keySet().stream().sorted().forEach(namespace -> {
                try {
                    jg.writeStartObject();
                    jg.writeStringField("id", namespace.getEncoded());
                    jg.writeStringField("text", namespace.getDecoded());
                    jg.writeFieldName("children");
                    jg.writeStartArray();
                    groupedIds.get(namespace).forEach(id -> {
                        try {
                            jg.writeStartObject();
                            String text;
                            if (supportsNameAttribute) {
                                AbstractComponentInstanceResource componentInstaceResource = AbstractComponentsResource
                                        .getComponentInstaceResource(id);
                                text = ((IHasName) componentInstaceResource).getName();
                            } else {
                                text = id.getXmlId().getDecoded();
                            }
                            jg.writeStringField("id", id.getQName().toString());
                            jg.writeStringField("text", text);
                            jg.writeEndObject();
                        } catch (IOException e) {
                            AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                        }
                    });
                    jg.writeEndArray();
                    jg.writeEndObject();
                } catch (IOException e) {
                    AbstractComponentsResource.LOGGER.error("Could not create JSON", e);
                }
            });
            jg.writeEndArray();
        }
        jg.close();
    } catch (Exception e) {
        AbstractComponentsResource.LOGGER.error(e.getMessage(), e);
        return "[]";
    }
    return sw.toString();
}

From source file:org.eclipse.winery.repository.rest.resources._support.AbstractComponentsResource.java

private List<NamespaceAndDefinedLocalNamesForAngular> getGroupedListOfIds(
        SortedSet<? extends DefinitionsChildId> allDefinitionsChildIds, String full, String includeVersions) {
    Map<Namespace, ? extends List<? extends DefinitionsChildId>> groupedIds = allDefinitionsChildIds.stream()
            .collect(Collectors.groupingBy(DefinitionsChildId::getNamespace));
    return groupedIds.keySet().stream().sorted().map(namespace -> {
        List<LocalNameForAngular> names = groupedIds.get(namespace).stream().map(definition -> {
            Definitions fullDefinition = null;
            if (Objects.nonNull(full)) {
                fullDefinition = getFullComponentData(definition);
            }/*w w w. j a v a2  s . com*/

            String qName = definition.getQName().toString();
            String id = definition.getXmlId().toString();

            if ("componentVersionOnly".equals(includeVersions)) {
                qName = VersionUtils.getQNameWithComponentVersionOnly(definition);
                id = qName.split("}")[1];
            }

            return new LocalNameForAngular(qName, id, fullDefinition);
        }).distinct().collect(Collectors.toList());

        return new NamespaceAndDefinedLocalNamesForAngular(namespace, names);
    }).collect(Collectors.toList());
}

From source file:org.hswebframework.web.service.authorization.simple.SimpleAuthorizationSettingService.java

private List<AuthorizationSettingEntity> getUserSetting(String userId) {
    Map<String, List<SettingInfo>> settingInfo = authorizationSettingTypeSuppliers.stream()
            .map(supplier -> supplier.get(userId)).flatMap(Set::stream)
            .collect(Collectors.groupingBy(SettingInfo::getType));
    Stream<Map.Entry<String, List<SettingInfo>>> settingInfoStream = settingInfo.entrySet().stream();
    //1 ?//from w  w w.  j a va 2 s.c  o  m
    if (settingInfo.size() > 1) {
        settingInfoStream = settingInfoStream.parallel();
    }
    return settingInfoStream.map(entry -> createQuery()
            // where type = ? and setting_for in (?,?,?....)
            .where(type, entry.getKey()).and()
            .in(settingFor,
                    entry.getValue().stream().map(SettingInfo::getSettingFor).collect(Collectors.toList()))
            .listNoPaging()).flatMap(List::stream).collect(Collectors.toList());
}

From source file:org.hswebframework.web.service.authorization.simple.SimpleAuthorizationSettingService.java

@Override
public Authentication initUserAuthorization(String userId) {
    if (null == userId) {
        return null;
    }//from w ww  . ja v  a2s.  c o  m
    UserEntity userEntity = userService.selectByPk(userId);
    if (userEntity == null) {
        return null;
    }
    SimpleAuthentication authentication = new SimpleAuthentication();
    // ?
    authentication.setUser(SimpleUser.builder().id(userId).username(userEntity.getUsername())
            .name(userEntity.getName()).type("default").build());
    //
    authentication.setRoles(userService.getUserRole(userId).stream()
            .map(role -> new SimpleRole(role.getId(), role.getName())).collect(Collectors.toList()));

    List<String> settingIdList = getUserSetting(userId).stream().map(AuthorizationSettingEntity::getId)
            .collect(Collectors.toList());

    if (settingIdList.isEmpty()) {
        authentication.setPermissions(new ArrayList<>());
        return authentication;
    }

    // where status=1 and setting_id in (?,?,?)
    List<AuthorizationSettingDetailEntity> detailList = DefaultDSLQueryService
            .createQuery(authorizationSettingDetailDao).where(status, STATE_OK).and()
            .in(settingId, settingIdList).listNoPaging();
    //??id?
    List<String> permissionIds = detailList.stream().map(AuthorizationSettingDetailEntity::getPermissionId)
            .distinct().collect(Collectors.toList());
    //???
    Map<String, PermissionEntity> permissionEntityCache = permissionService.selectByPk(permissionIds).stream()
            .collect(Collectors.toMap(PermissionEntity::getId, Function.identity()));

    //?
    detailList = detailList.stream().filter(detail -> {
        PermissionEntity entity = permissionEntityCache.get(detail.getPermissionId());
        if (entity == null || !STATUS_ENABLED.equals(entity.getStatus())) {
            return false;
        }
        List<String> allActions = entity.getActions().stream().map(ActionEntity::getAction)
                .collect(Collectors.toList());

        if (isNotEmpty(entity.getActions()) && isNotEmpty(detail.getActions())) {

            detail.setActions(
                    detail.getActions().stream().filter(allActions::contains).collect(Collectors.toSet()));
        }
        if (isEmpty(entity.getSupportDataAccessTypes())) {
            detail.setDataAccesses(new java.util.ArrayList<>());
        } else if (isNotEmpty(detail.getDataAccesses()) && !entity.getSupportDataAccessTypes().contains("*")) {
            //????????,???
            detail.setDataAccesses(detail.getDataAccesses().stream().filter(access ->
            //?????
            //???CUSTOM_SCOPE_ORG_SCOPE
            //??CUSTOM_SCOPE 
            entity.getSupportDataAccessTypes().stream().anyMatch(type -> type.startsWith(access.getType())))
                    .collect(Collectors.toList()));
        }
        return true;
    }).collect(Collectors.toList());

    //??
    Map<String, List<AuthorizationSettingDetailEntity>> settings = detailList.stream()
            .collect(Collectors.groupingBy(AuthorizationSettingDetailEntity::getPermissionId));

    List<Permission> permissions = new ArrayList<>();
    //?????
    Map<String, List<ParentPermission>> parentsPermissions = permissionEntityCache.values().stream()
            .map(PermissionEntity::getParents).filter(Objects::nonNull).flatMap(Collection::stream)
            .collect(Collectors.groupingBy(ParentPermission::getPermission));

    settings.forEach((permissionId, details) -> {
        SimplePermission permission = new SimplePermission();
        permission.setId(permissionId);
        Set<String> actions = new HashSet<>();
        Set<DataAccessConfig> dataAccessConfigs = new HashSet<>();
        //?,??
        Collections.sort(details);
        for (AuthorizationSettingDetailEntity detail : details) {
            //????,??
            if (Boolean.FALSE.equals(detail.getMerge())) {
                actions.clear();
                dataAccessConfigs.clear();
            }
            // actions
            if (null != detail.getActions()) {
                actions.addAll(detail.getActions());
            }
            // ????
            if (null != detail.getDataAccesses()) {
                dataAccessConfigs.addAll(detail.getDataAccesses().stream().map(dataAccessFactory::create)
                        .collect(Collectors.toSet()));
            }
        }
        //??????
        List<ParentPermission> parents = parentsPermissions.get(permissionId);
        if (parents != null) {
            actions.addAll(parents.stream().map(ParentPermission::getActions).filter(Objects::nonNull)
                    .flatMap(Collection::stream).collect(Collectors.toSet()));
            parentsPermissions.remove(permissionId);
        }
        permission.setActions(actions);
        permission.setDataAccesses(dataAccessConfigs);
        permissions.add(permission);
    });

    //???
    parentsPermissions.forEach((per, all) -> {
        SimplePermission permission = new SimplePermission();
        permission.setId(per);
        permission.setActions(all.stream().map(ParentPermission::getActions).filter(Objects::nonNull)
                .flatMap(Collection::stream).collect(Collectors.toSet()));
        permissions.add(permission);
    });
    authentication.setPermissions(permissions);
    return authentication;
}

From source file:org.kuali.coeus.common.committee.impl.lookup.CommitteeLookupableHelperServiceImplBase.java

protected Map<String, String> getLatestDocumentNumber(List<CMT> committees, String routeHeaderCode) {
    return committees.stream()
            .filter(committee -> committee.getCommitteeDocument().getDocStatusCode().equals(routeHeaderCode))
            .collect(Collectors.groupingBy(committee -> committee.getCommitteeId())).entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey,
                    value -> value.getValue().stream()
                            .max(Comparator.comparingInt(committee -> committee.getSequenceNumber())).get()
                            .getCommitteeDocument().getDocumentNumber()));
}

From source file:org.lenskit.data.store.PackedEntityCollection.java

@Override
public Map<Long, List<Entity>> grouped(TypedName<Long> attr) {
    Preconditions.checkArgument(attr != CommonAttributes.ENTITY_ID, "cannot group by entity ID");
    int idx = attributes.lookup(attr);
    if (idx < 0) {
        return Collections.emptyMap();
    }//from   w ww .  j  a v  a  2s  .c  o m

    PackIndex index = indexes[idx];
    if (index != null) {
        return index.getValues().stream()
                .collect(Collectors.toMap(l -> (Long) l, l -> new EntityList(index.getPositions(l))));
    } else {
        return stream().filter(e -> e.hasAttribute(attr)).collect(Collectors.groupingBy(e -> e.getLong(attr)));
    }
}