java.util.stream.Collectors.groupingBy()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(422)

本文整理了Java中java.util.stream.Collectors.groupingBy()方法的一些代码示例,展示了Collectors.groupingBy()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collectors.groupingBy()方法的具体详情如下:
包路径:java.util.stream.Collectors
类名称:Collectors
方法名:groupingBy

Collectors.groupingBy介绍

暂无

代码示例

代码示例来源:origin: neo4j/neo4j

  1. private Stream<Map.Entry<String,List<Element>>> indexByName( Collection<Element> visitedProcedures )
  2. {
  3. return visitedProcedures.stream().collect( groupingBy( this::getName ) ).entrySet().stream();
  4. }

代码示例来源:origin: google/error-prone

  1. /**
  2. * Returns a collection of method groups for given list of {@code classMethods}.
  3. *
  4. * <p>A <i>method group</i> is a list of methods with the same name.
  5. *
  6. * <p>It is assumed that given {@code classMethods} really do belong to the same class. The
  7. * returned collection does not guarantee any particular group ordering.
  8. */
  9. private static Collection<List<MethodTree>> getMethodGroups(List<MethodTree> classMethods) {
  10. return classMethods.stream().collect(groupingBy(MethodTree::getName)).values();
  11. }

代码示例来源:origin: SonarSource/sonarqube

  1. public Helper() {
  2. InputStream inputStream = Helper.class.getResourceAsStream("/responseClasses.config");
  3. responseTypes = new BufferedReader(new InputStreamReader(inputStream))
  4. .lines()
  5. .map(line -> line.split("\\s+"))
  6. .collect(Collectors.groupingBy(arr -> arr[0]));
  7. }

代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises

  1. public Map<Artist, Integer> numberOfAlbumsDumb(Stream<Album> albums) {
  2. // BEGIN NUMBER_OF_ALBUMS_DUMB
  3. Map<Artist, List<Album>> albumsByArtist
  4. = albums.collect(groupingBy(album -> album.getMainMusician()));
  5. Map<Artist, Integer> numberOfAlbums = new HashMap<>();
  6. for(Entry<Artist, List<Album>> entry : albumsByArtist.entrySet()) {
  7. numberOfAlbums.put(entry.getKey(), entry.getValue().size());
  8. }
  9. // END NUMBER_OF_ALBUMS_DUMB
  10. return numberOfAlbums;
  11. }

代码示例来源:origin: goldmansachs/gs-collections

  1. @Benchmark
  2. public Map<Boolean, Set<Integer>> groupBy_2_keys_serial_lazy_jdk()
  3. {
  4. Map<Boolean, Set<Integer>> multimap = this.integersJDK.stream()
  5. .collect(Collectors.groupingBy(each -> each % 2 == 0, Collectors.toSet()));
  6. Verify.assertSize(2, multimap);
  7. return multimap;
  8. }

代码示例来源:origin: confluentinc/ksql

  1. public static Collection<Double> currentConsumptionRateByQuery() {
  2. return collectorMap.values()
  3. .stream()
  4. .filter(collector -> collector.getGroupId() != null)
  5. .collect(
  6. Collectors.groupingBy(
  7. MetricCollector::getGroupId,
  8. Collectors.summingDouble(
  9. m -> m.aggregateStat(ConsumerCollector.CONSUMER_MESSAGES_PER_SEC, false)
  10. )
  11. )
  12. )
  13. .values();
  14. }

代码示例来源:origin: stackoverflow.com

  1. import java.util.*;
  2. import java.util.stream.*;
  3. class Test {
  4. public static void main(String[] args) {
  5. List<String> list = new ArrayList<>();
  6. list.add("Hello");
  7. list.add("Hello");
  8. list.add("World");
  9. Map<String, Long> counted = list.stream()
  10. .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
  11. System.out.println(counted);
  12. }
  13. }

代码示例来源:origin: apache/flink

  1. @Override
  2. @Nonnull
  3. Map<String, String> expected(@Nonnull List<ValueWithTs<Tuple2<String, String>>> updates, long currentTimestamp) {
  4. return updates.stream()
  5. .collect(Collectors.groupingBy(u -> u.getValue().f0))
  6. .entrySet().stream()
  7. .map(e -> e.getValue().get(e.getValue().size() - 1))
  8. .filter(u -> !expired(u.getTimestamp(), currentTimestamp))
  9. .map(ValueWithTs::getValue)
  10. .collect(Collectors.toMap(u -> u.f0, u -> u.f1));
  11. }
  12. }

代码示例来源:origin: apache/storm

  1. private Collection<List<ProcessorNode>> parallelismGroups(List<ProcessorNode> processorNodes) {
  2. return processorNodes.stream().collect(Collectors.groupingBy(Node::getParallelism)).values();
  3. }

代码示例来源:origin: apache/nifi

  1. public Map<QueuePartition, List<FlowFileRecord>> distributeToPartitionsAndGet(final Collection<FlowFileRecord> flowFiles) {
  2. if (flowFiles == null || flowFiles.isEmpty()) {
  3. return Collections.emptyMap();
  4. }
  5. final Map<QueuePartition, List<FlowFileRecord>> partitionMap;
  6. partitionReadLock.lock();
  7. try {
  8. // Optimize for the most common case (no load balancing) so that we will just call getPartition() for the first FlowFile
  9. // in the Collection and then put all FlowFiles into that QueuePartition. Is fairly expensive to call stream().collect(#groupingBy).
  10. if (partitioner.isPartitionStatic()) {
  11. final QueuePartition partition = getPartition(flowFiles.iterator().next());
  12. partition.putAll(flowFiles);
  13. final List<FlowFileRecord> flowFileList = (flowFiles instanceof List) ? (List<FlowFileRecord>) flowFiles : new ArrayList<>(flowFiles);
  14. partitionMap = Collections.singletonMap(partition, flowFileList);
  15. logger.debug("Partitioner is static so Partitioned FlowFiles as: {}", partitionMap);
  16. return partitionMap;
  17. }
  18. partitionMap = flowFiles.stream().collect(Collectors.groupingBy(this::getPartition));
  19. logger.debug("Partitioned FlowFiles as: {}", partitionMap);
  20. for (final Map.Entry<QueuePartition, List<FlowFileRecord>> entry : partitionMap.entrySet()) {
  21. final QueuePartition partition = entry.getKey();
  22. final List<FlowFileRecord> flowFilesForPartition = entry.getValue();
  23. partition.putAll(flowFilesForPartition);
  24. }
  25. } finally {
  26. partitionReadLock.unlock();
  27. }
  28. return partitionMap;
  29. }

代码示例来源:origin: goldmansachs/gs-collections

  1. @Benchmark
  2. public Map<Integer, Set<Integer>> groupBy_100_keys_serial_lazy_jdk()
  3. {
  4. Map<Integer, Set<Integer>> multimap = this.integersJDK.stream().collect(Collectors.groupingBy(each -> each % 100, Collectors.toSet()));
  5. Verify.assertSize(100, multimap);
  6. return multimap;
  7. }

代码示例来源:origin: gocd/gocd

  1. public Collection<CombinedPluginInfo> allPluginInfos(String type) {
  2. if (isBlank(type)) {
  3. return builders.values().stream()
  4. .map((Function<MetadataStore, Collection<? extends PluginInfo>>) MetadataStore::allPluginInfos)
  5. .flatMap((Function<Collection<? extends PluginInfo>, Stream<? extends PluginInfo>>) Collection::stream)
  6. .collect(Collectors.groupingBy(pluginID(), toCollection(CombinedPluginInfo::new)))
  7. .values();
  8. } else if (builders.containsKey(type)) {
  9. Collection<PluginInfo> pluginInfosForType = builders.get(type).allPluginInfos();
  10. return pluginInfosForType.stream()
  11. .map(CombinedPluginInfo::new).collect(toList());
  12. } else {
  13. throw new InvalidPluginTypeException();
  14. }
  15. }

代码示例来源:origin: Graylog2/graylog2-server

  1. @GET
  2. @RequiresPermissions(RestPermissions.USERS_LIST)
  3. @ApiOperation(value = "List all users", notes = "The permissions assigned to the users are always included.")
  4. public UserList listUsers() {
  5. final List<User> users = userService.loadAll();
  6. final Collection<MongoDbSession> sessions = sessionService.loadAll();
  7. // among all active sessions, find the last recently used for each user
  8. //noinspection OptionalGetWithoutIsPresent
  9. final Map<String, Optional<MongoDbSession>> lastSessionForUser = sessions.stream()
  10. .filter(s -> s.getUsernameAttribute().isPresent())
  11. .collect(groupingBy(s -> s.getUsernameAttribute().get(),
  12. maxBy(Comparator.comparing(MongoDbSession::getLastAccessTime))));
  13. final List<UserSummary> resultUsers = Lists.newArrayListWithCapacity(users.size() + 1);
  14. final User adminUser = userService.getAdminUser();
  15. resultUsers.add(toUserResponse(adminUser, lastSessionForUser.getOrDefault(adminUser.getName(), Optional.empty())));
  16. for (User user : users) {
  17. resultUsers.add(toUserResponse(user, lastSessionForUser.getOrDefault(user.getName(), Optional.empty())));
  18. }
  19. return UserList.create(resultUsers);
  20. }

代码示例来源:origin: languagetool-org/languagetool

  1. private void updateIgnoredWordDictionary() {
  2. wordsToBeIgnoredDictionary = wordsToBeIgnored
  3. .stream()
  4. .collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toSet()));
  5. wordsToBeIgnoredDictionaryIgnoreCase = wordsToBeIgnored
  6. .stream()
  7. .map(s -> s.toLowerCase())
  8. .collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toSet()));
  9. }

代码示例来源:origin: neo4j/neo4j

  1. public void forEach( BiConsumer<String,URI> consumer )
  2. {
  3. entries.stream().collect( Collectors.groupingBy( e -> e.key ) )
  4. .forEach( ( key, list ) -> list.stream()
  5. .max( Comparator.comparing( e -> e.precedence ) )
  6. .ifPresent( e -> consumer.accept( key, e.uri ) ) );
  7. }

代码示例来源:origin: checkstyle/checkstyle

  1. /**
  2. * Generate the map of third party Checkstyle module names to the set of their fully qualified
  3. * names.
  4. * @param loader the class loader used to load Checkstyle package names
  5. * @return the map of third party Checkstyle module names to the set of their fully qualified
  6. * names
  7. */
  8. private Map<String, Set<String>> generateThirdPartyNameToFullModuleName(ClassLoader loader) {
  9. Map<String, Set<String>> returnValue;
  10. try {
  11. returnValue = ModuleReflectionUtil.getCheckstyleModules(packages, loader).stream()
  12. .collect(Collectors.groupingBy(Class::getSimpleName,
  13. Collectors.mapping(Class::getCanonicalName, Collectors.toSet())));
  14. }
  15. catch (IOException ignore) {
  16. returnValue = Collections.emptyMap();
  17. }
  18. return returnValue;
  19. }

代码示例来源:origin: SonarSource/sonarqube

  1. private static void ensureNoDuplicateName(Set<CoreExtension> coreExtensions) {
  2. Map<String, Long> nameCounts = coreExtensions.stream()
  3. .map(CoreExtension::getName)
  4. .collect(Collectors.groupingBy(t -> t, Collectors.counting()));
  5. Set<String> duplicatedNames = nameCounts.entrySet().stream()
  6. .filter(t -> t.getValue() > 1)
  7. .map(Map.Entry::getKey)
  8. .collect(MoreCollectors.toSet());
  9. checkState(duplicatedNames.isEmpty(),
  10. "Multiple core extensions declare the following names: %s",
  11. duplicatedNames.stream().sorted().collect(Collectors.joining(", ")));
  12. }

代码示例来源:origin: neo4j/neo4j

  1. private Map<AdminCommandSection,List<AdminCommand.Provider>> groupProvidersBySection()
  2. {
  3. List<AdminCommand.Provider> providers = new ArrayList<>();
  4. commands.getAllProviders().forEach( providers::add );
  5. return providers.stream().collect( Collectors.groupingBy( AdminCommand.Provider::commandSection ) );
  6. }
  7. }

代码示例来源:origin: apache/nifi

  1. /**
  2. * Set input or output DataSet ids for a NiFiFlowPath.
  3. * The updated ids only containing active ids.
  4. * @return True if there is any changed IO reference (create, update, delete).
  5. */
  6. private boolean setChangedIOIds(NiFiFlowPath path, AtlasEntity pathEntity, boolean isInput) {
  7. Set<AtlasObjectId> ids = isInput ? path.getInputs() : path.getOutputs();
  8. String targetAttribute = isInput ? ATTR_INPUTS : ATTR_OUTPUTS;
  9. final Map<EntityChangeType, List<AtlasObjectId>> changedIOIds
  10. = ids.stream().collect(Collectors.groupingBy(this::getFlowPathIOChangeType));
  11. // Remove DELETED references.
  12. final Set<AtlasObjectId> remainingFlowPathIOIds = toRemainingFlowPathIOIds(changedIOIds);
  13. // If references are changed, update it.
  14. if (path.isDataSetReferenceChanged(remainingFlowPathIOIds, isInput)) {
  15. pathEntity.setAttribute(targetAttribute, remainingFlowPathIOIds);
  16. return true;
  17. }
  18. return false;
  19. }

代码示例来源:origin: Graylog2/graylog2-server

  1. @Override
  2. public Map<String, List<StreamRule>> loadForStreamIds(Collection<String> streamIds) {
  3. final List<ObjectId> objectIds = streamIds.stream()
  4. .map(ObjectId::new)
  5. .collect(Collectors.toList());
  6. final List<DBObject> respStreamRules = query(StreamRuleImpl.class,
  7. new BasicDBObject(StreamRuleImpl.FIELD_STREAM_ID, new BasicDBObject("$in", objectIds))
  8. );
  9. return respStreamRules.stream()
  10. .map(this::toStreamRule)
  11. .collect(Collectors.groupingBy(StreamRule::getStreamId));
  12. }

相关文章