本文整理了Java中java.util.stream.Collectors.groupingBy()
方法的一些代码示例,展示了Collectors.groupingBy()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collectors.groupingBy()
方法的具体详情如下:
包路径:java.util.stream.Collectors
类名称:Collectors
方法名:groupingBy
暂无
代码示例来源:origin: neo4j/neo4j
private Stream<Map.Entry<String,List<Element>>> indexByName( Collection<Element> visitedProcedures )
{
return visitedProcedures.stream().collect( groupingBy( this::getName ) ).entrySet().stream();
}
代码示例来源:origin: google/error-prone
/**
* Returns a collection of method groups for given list of {@code classMethods}.
*
* <p>A <i>method group</i> is a list of methods with the same name.
*
* <p>It is assumed that given {@code classMethods} really do belong to the same class. The
* returned collection does not guarantee any particular group ordering.
*/
private static Collection<List<MethodTree>> getMethodGroups(List<MethodTree> classMethods) {
return classMethods.stream().collect(groupingBy(MethodTree::getName)).values();
}
代码示例来源:origin: SonarSource/sonarqube
public Helper() {
InputStream inputStream = Helper.class.getResourceAsStream("/responseClasses.config");
responseTypes = new BufferedReader(new InputStreamReader(inputStream))
.lines()
.map(line -> line.split("\\s+"))
.collect(Collectors.groupingBy(arr -> arr[0]));
}
代码示例来源:origin: RichardWarburton/java-8-lambdas-exercises
public Map<Artist, Integer> numberOfAlbumsDumb(Stream<Album> albums) {
// BEGIN NUMBER_OF_ALBUMS_DUMB
Map<Artist, List<Album>> albumsByArtist
= albums.collect(groupingBy(album -> album.getMainMusician()));
Map<Artist, Integer> numberOfAlbums = new HashMap<>();
for(Entry<Artist, List<Album>> entry : albumsByArtist.entrySet()) {
numberOfAlbums.put(entry.getKey(), entry.getValue().size());
}
// END NUMBER_OF_ALBUMS_DUMB
return numberOfAlbums;
}
代码示例来源:origin: goldmansachs/gs-collections
@Benchmark
public Map<Boolean, Set<Integer>> groupBy_2_keys_serial_lazy_jdk()
{
Map<Boolean, Set<Integer>> multimap = this.integersJDK.stream()
.collect(Collectors.groupingBy(each -> each % 2 == 0, Collectors.toSet()));
Verify.assertSize(2, multimap);
return multimap;
}
代码示例来源:origin: confluentinc/ksql
public static Collection<Double> currentConsumptionRateByQuery() {
return collectorMap.values()
.stream()
.filter(collector -> collector.getGroupId() != null)
.collect(
Collectors.groupingBy(
MetricCollector::getGroupId,
Collectors.summingDouble(
m -> m.aggregateStat(ConsumerCollector.CONSUMER_MESSAGES_PER_SEC, false)
)
)
)
.values();
}
代码示例来源:origin: stackoverflow.com
import java.util.*;
import java.util.stream.*;
class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("World");
Map<String, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counted);
}
}
代码示例来源:origin: apache/flink
@Override
@Nonnull
Map<String, String> expected(@Nonnull List<ValueWithTs<Tuple2<String, String>>> updates, long currentTimestamp) {
return updates.stream()
.collect(Collectors.groupingBy(u -> u.getValue().f0))
.entrySet().stream()
.map(e -> e.getValue().get(e.getValue().size() - 1))
.filter(u -> !expired(u.getTimestamp(), currentTimestamp))
.map(ValueWithTs::getValue)
.collect(Collectors.toMap(u -> u.f0, u -> u.f1));
}
}
代码示例来源:origin: apache/storm
private Collection<List<ProcessorNode>> parallelismGroups(List<ProcessorNode> processorNodes) {
return processorNodes.stream().collect(Collectors.groupingBy(Node::getParallelism)).values();
}
代码示例来源:origin: apache/nifi
public Map<QueuePartition, List<FlowFileRecord>> distributeToPartitionsAndGet(final Collection<FlowFileRecord> flowFiles) {
if (flowFiles == null || flowFiles.isEmpty()) {
return Collections.emptyMap();
}
final Map<QueuePartition, List<FlowFileRecord>> partitionMap;
partitionReadLock.lock();
try {
// Optimize for the most common case (no load balancing) so that we will just call getPartition() for the first FlowFile
// in the Collection and then put all FlowFiles into that QueuePartition. Is fairly expensive to call stream().collect(#groupingBy).
if (partitioner.isPartitionStatic()) {
final QueuePartition partition = getPartition(flowFiles.iterator().next());
partition.putAll(flowFiles);
final List<FlowFileRecord> flowFileList = (flowFiles instanceof List) ? (List<FlowFileRecord>) flowFiles : new ArrayList<>(flowFiles);
partitionMap = Collections.singletonMap(partition, flowFileList);
logger.debug("Partitioner is static so Partitioned FlowFiles as: {}", partitionMap);
return partitionMap;
}
partitionMap = flowFiles.stream().collect(Collectors.groupingBy(this::getPartition));
logger.debug("Partitioned FlowFiles as: {}", partitionMap);
for (final Map.Entry<QueuePartition, List<FlowFileRecord>> entry : partitionMap.entrySet()) {
final QueuePartition partition = entry.getKey();
final List<FlowFileRecord> flowFilesForPartition = entry.getValue();
partition.putAll(flowFilesForPartition);
}
} finally {
partitionReadLock.unlock();
}
return partitionMap;
}
代码示例来源:origin: goldmansachs/gs-collections
@Benchmark
public Map<Integer, Set<Integer>> groupBy_100_keys_serial_lazy_jdk()
{
Map<Integer, Set<Integer>> multimap = this.integersJDK.stream().collect(Collectors.groupingBy(each -> each % 100, Collectors.toSet()));
Verify.assertSize(100, multimap);
return multimap;
}
代码示例来源:origin: gocd/gocd
public Collection<CombinedPluginInfo> allPluginInfos(String type) {
if (isBlank(type)) {
return builders.values().stream()
.map((Function<MetadataStore, Collection<? extends PluginInfo>>) MetadataStore::allPluginInfos)
.flatMap((Function<Collection<? extends PluginInfo>, Stream<? extends PluginInfo>>) Collection::stream)
.collect(Collectors.groupingBy(pluginID(), toCollection(CombinedPluginInfo::new)))
.values();
} else if (builders.containsKey(type)) {
Collection<PluginInfo> pluginInfosForType = builders.get(type).allPluginInfos();
return pluginInfosForType.stream()
.map(CombinedPluginInfo::new).collect(toList());
} else {
throw new InvalidPluginTypeException();
}
}
代码示例来源:origin: Graylog2/graylog2-server
@GET
@RequiresPermissions(RestPermissions.USERS_LIST)
@ApiOperation(value = "List all users", notes = "The permissions assigned to the users are always included.")
public UserList listUsers() {
final List<User> users = userService.loadAll();
final Collection<MongoDbSession> sessions = sessionService.loadAll();
// among all active sessions, find the last recently used for each user
//noinspection OptionalGetWithoutIsPresent
final Map<String, Optional<MongoDbSession>> lastSessionForUser = sessions.stream()
.filter(s -> s.getUsernameAttribute().isPresent())
.collect(groupingBy(s -> s.getUsernameAttribute().get(),
maxBy(Comparator.comparing(MongoDbSession::getLastAccessTime))));
final List<UserSummary> resultUsers = Lists.newArrayListWithCapacity(users.size() + 1);
final User adminUser = userService.getAdminUser();
resultUsers.add(toUserResponse(adminUser, lastSessionForUser.getOrDefault(adminUser.getName(), Optional.empty())));
for (User user : users) {
resultUsers.add(toUserResponse(user, lastSessionForUser.getOrDefault(user.getName(), Optional.empty())));
}
return UserList.create(resultUsers);
}
代码示例来源:origin: languagetool-org/languagetool
private void updateIgnoredWordDictionary() {
wordsToBeIgnoredDictionary = wordsToBeIgnored
.stream()
.collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toSet()));
wordsToBeIgnoredDictionaryIgnoreCase = wordsToBeIgnored
.stream()
.map(s -> s.toLowerCase())
.collect(Collectors.groupingBy(s -> s.substring(0,1), Collectors.toSet()));
}
代码示例来源:origin: neo4j/neo4j
public void forEach( BiConsumer<String,URI> consumer )
{
entries.stream().collect( Collectors.groupingBy( e -> e.key ) )
.forEach( ( key, list ) -> list.stream()
.max( Comparator.comparing( e -> e.precedence ) )
.ifPresent( e -> consumer.accept( key, e.uri ) ) );
}
代码示例来源:origin: checkstyle/checkstyle
/**
* Generate the map of third party Checkstyle module names to the set of their fully qualified
* names.
* @param loader the class loader used to load Checkstyle package names
* @return the map of third party Checkstyle module names to the set of their fully qualified
* names
*/
private Map<String, Set<String>> generateThirdPartyNameToFullModuleName(ClassLoader loader) {
Map<String, Set<String>> returnValue;
try {
returnValue = ModuleReflectionUtil.getCheckstyleModules(packages, loader).stream()
.collect(Collectors.groupingBy(Class::getSimpleName,
Collectors.mapping(Class::getCanonicalName, Collectors.toSet())));
}
catch (IOException ignore) {
returnValue = Collections.emptyMap();
}
return returnValue;
}
代码示例来源:origin: SonarSource/sonarqube
private static void ensureNoDuplicateName(Set<CoreExtension> coreExtensions) {
Map<String, Long> nameCounts = coreExtensions.stream()
.map(CoreExtension::getName)
.collect(Collectors.groupingBy(t -> t, Collectors.counting()));
Set<String> duplicatedNames = nameCounts.entrySet().stream()
.filter(t -> t.getValue() > 1)
.map(Map.Entry::getKey)
.collect(MoreCollectors.toSet());
checkState(duplicatedNames.isEmpty(),
"Multiple core extensions declare the following names: %s",
duplicatedNames.stream().sorted().collect(Collectors.joining(", ")));
}
代码示例来源:origin: neo4j/neo4j
private Map<AdminCommandSection,List<AdminCommand.Provider>> groupProvidersBySection()
{
List<AdminCommand.Provider> providers = new ArrayList<>();
commands.getAllProviders().forEach( providers::add );
return providers.stream().collect( Collectors.groupingBy( AdminCommand.Provider::commandSection ) );
}
}
代码示例来源:origin: apache/nifi
/**
* Set input or output DataSet ids for a NiFiFlowPath.
* The updated ids only containing active ids.
* @return True if there is any changed IO reference (create, update, delete).
*/
private boolean setChangedIOIds(NiFiFlowPath path, AtlasEntity pathEntity, boolean isInput) {
Set<AtlasObjectId> ids = isInput ? path.getInputs() : path.getOutputs();
String targetAttribute = isInput ? ATTR_INPUTS : ATTR_OUTPUTS;
final Map<EntityChangeType, List<AtlasObjectId>> changedIOIds
= ids.stream().collect(Collectors.groupingBy(this::getFlowPathIOChangeType));
// Remove DELETED references.
final Set<AtlasObjectId> remainingFlowPathIOIds = toRemainingFlowPathIOIds(changedIOIds);
// If references are changed, update it.
if (path.isDataSetReferenceChanged(remainingFlowPathIOIds, isInput)) {
pathEntity.setAttribute(targetAttribute, remainingFlowPathIOIds);
return true;
}
return false;
}
代码示例来源:origin: Graylog2/graylog2-server
@Override
public Map<String, List<StreamRule>> loadForStreamIds(Collection<String> streamIds) {
final List<ObjectId> objectIds = streamIds.stream()
.map(ObjectId::new)
.collect(Collectors.toList());
final List<DBObject> respStreamRules = query(StreamRuleImpl.class,
new BasicDBObject(StreamRuleImpl.FIELD_STREAM_ID, new BasicDBObject("$in", objectIds))
);
return respStreamRules.stream()
.map(this::toStreamRule)
.collect(Collectors.groupingBy(StreamRule::getStreamId));
}
内容来源于网络,如有侵权,请联系作者删除!