LongPositions(Iterable<? extends Object> elements, final int bitPerLong) {
this.elements = ImmutableList.copyOf(elements);
checkArgument(bitPerLong <= BITS_IN_LONG, bitPerLong);
for (int i = 0; i < this.elements.size(); i++) {
positions.put(
this.elements.get(i),
new BitPosition(
i / bitPerLong,
i % bitPerLong));
}
this.longPositions = ImmutableSortedMap.copyOf(
Maps.transformEntries(
Multimaps.index(positions.values(), ToLongIndex.FUNCTION).asMap(),
new Maps.EntryTransformer<Integer, Collection<BitPosition>, LongSet>() {
@Override
public LongSet transformEntry(Integer key, Collection<BitPosition> position) {
return new LongSet(key, position);
}
}));
}
java类com.google.common.collect.Multimaps的实例源码
LongBits.java 文件源码
项目:GitHub
阅读 70
收藏 0
点赞 0
评论 0
TaskManager.java 文件源码
项目:HardVox
阅读 52
收藏 0
点赞 0
评论 0
public void runTasks() {
Multimaps.asMap(ImmutableListMultimap.copyOf(taskQueue)).values().forEach(tasks -> {
int size = tasks.size();
while (size > 0) {
int last = size - 1;
Task<?> current = tasks.get(last);
if (current.done()) {
taskQueue.get(current.getClass()).remove(last);
size--;
continue;
}
current.tick();
return;
}
});
}
ImpactAnalysisTool.java 文件源码
项目:powsybl-core
阅读 26
收藏 0
点赞 0
评论 0
private static Multimap<String, SecurityIndex> runImpactAnalysis(Network network, Set<String> contingencyIds,
ComputationManager computationManager, SimulatorFactory simulatorFactory,
ContingenciesProvider contingenciesProvider,
PrintStream out) throws Exception {
Stabilization stabilization = simulatorFactory.createStabilization(network, computationManager, 0);
ImpactAnalysis impactAnalysis = simulatorFactory.createImpactAnalysis(network, computationManager, 0, contingenciesProvider);
Map<String, Object> initContext = new HashMap<>();
SimulationParameters simulationParameters = SimulationParameters.load();
stabilization.init(simulationParameters, initContext);
impactAnalysis.init(simulationParameters, initContext);
out.println("running stabilization simulation...");
StabilizationResult sr = stabilization.run();
out.println("stabilization status: " + sr.getStatus());
out.println("stabilization metrics: " + sr.getMetrics());
if (sr.getStatus() == StabilizationStatus.COMPLETED) {
out.println("running impact analysis...");
ImpactAnalysisResult iar = impactAnalysis.run(sr.getState(), contingencyIds);
out.println("impact analysis metrics: " + iar.getMetrics());
return Multimaps.index(iar.getSecurityIndexes(), securityIndex -> securityIndex.getId().getContingencyId());
}
return null;
}
_CorpusQueryAssessments.java 文件源码
项目:tac-kbp-eal
阅读 25
收藏 0
点赞 0
评论 0
public final CorpusQueryAssessments filterForAssessment(final Set<QueryAssessment2016> assessment2016) {
final ImmutableSet.Builder<QueryResponse2016> matchingQueriesB = ImmutableSet.builder();
for (final QueryResponse2016 queryResponse2016 : assessments().keySet()) {
if (assessment2016.contains(assessments().get(queryResponse2016))) {
matchingQueriesB.add(queryResponse2016);
}
}
final ImmutableSet<QueryResponse2016> matchingQueries = matchingQueriesB.build();
final CorpusQueryAssessments.Builder ret = CorpusQueryAssessments.builder();
ret.queryReponses(matchingQueries);
ret.putAllQueryResponsesToSystemIDs(
Multimaps.filterKeys(queryResponsesToSystemIDs(), in(matchingQueries)));
ret.putAllMetadata(Maps.filterKeys(metadata(), in(matchingQueries)));
ret.putAllAssessments(Maps.filterKeys(assessments(), in(matchingQueries)));
return ret.build();
}
SameEventTypeLinker.java 文件源码
项目:tac-kbp-eal
阅读 30
收藏 0
点赞 0
评论 0
private ResponseLinking linkResponses(final Symbol docId,
final Iterable<Response> responses) {
final Predicate<Response> HasRelevantRealis =
compose(in(realisesWhichMustBeAligned), ResponseFunctions.realis());
final ImmutableSet<Response> systemResponsesAlignedRealis =
FluentIterable.from(responses).filter(HasRelevantRealis).toSet();
final Multimap<Symbol, Response> responsesByEventType =
Multimaps.index(systemResponsesAlignedRealis, ResponseFunctions.type());
final ImmutableSet.Builder<ResponseSet> ret = ImmutableSet.builder();
for (final Collection<Response> responseSet : responsesByEventType.asMap().values()) {
ret.add(ResponseSet.from(responseSet));
}
return ResponseLinking.builder().docID(docId).addAllResponseSets(ret.build()).build();
}
AbstractThriftMetadataBuilder.java 文件源码
项目:drift
阅读 39
收藏 0
点赞 0
评论 0
/**
* Assigns all fields an id if possible. Fields are grouped by name and for each group, if there
* is a single id, all fields in the group are assigned this id. If the group has multiple ids,
* an error is reported.
*/
protected final Set<String> inferThriftFieldIds()
{
Set<String> fieldsWithConflictingIds = new HashSet<>();
// group fields by explicit name or by name extracted from field, method or property
Multimap<String, FieldMetadata> fieldsByExplicitOrExtractedName = Multimaps.index(fields, FieldMetadata::getOrExtractThriftFieldName);
inferThriftFieldIds(fieldsByExplicitOrExtractedName, fieldsWithConflictingIds);
// group fields by name extracted from field, method or property
// this allows thrift name to be set explicitly without having to duplicate the name on getters and setters
// todo should this be the only way this works?
Multimap<String, FieldMetadata> fieldsByExtractedName = Multimaps.index(fields, FieldMetadata::extractName);
inferThriftFieldIds(fieldsByExtractedName, fieldsWithConflictingIds);
return fieldsWithConflictingIds;
}
MediaType.java 文件源码
项目:guava-mock
阅读 41
收藏 0
点赞 0
评论 0
private String computeToString() {
StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
if (!parameters.isEmpty()) {
builder.append("; ");
Multimap<String, String> quotedParameters =
Multimaps.transformValues(
parameters,
new Function<String, String>() {
@Override
public String apply(String value) {
return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
}
});
PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
}
return builder.toString();
}
AbstractIntegrationService.java 文件源码
项目:Equella
阅读 23
收藏 0
点赞 0
评论 0
private SetMultimap<String, IntegrationSessionExtension> getExtensionMap()
{
if( extensionMap == null )
{
synchronized( this )
{
if( extensionMap == null )
{
final SetMultimap<String, IntegrationSessionExtension> map = HashMultimap
.<String, IntegrationSessionExtension>create();
for( Extension ext : resultsTracker.getExtensions() )
{
final IntegrationSessionExtension integExtension = resultsTracker.getBeanByExtension(ext);
for( Parameter parameter : ext.getParameters("type") )
{
map.put(parameter.valueAsString(), integExtension);
}
}
extensionMap = Multimaps.unmodifiableSetMultimap(map);
}
}
}
return extensionMap;
}
DefaultRouter.java 文件源码
项目:athena
阅读 36
收藏 0
点赞 0
评论 0
@Activate
public void activate() {
ribTable4 = new ConcurrentInvertedRadixTree<>(
new DefaultByteArrayNodeFactory());
ribTable6 = new ConcurrentInvertedRadixTree<>(
new DefaultByteArrayNodeFactory());
routesWaitingOnArp = Multimaps.synchronizedSetMultimap(
HashMultimap.create());
coreService.registerApplication(ROUTER_APP_ID);
bgpUpdatesExecutor = Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder()
.setNameFormat("rib-updates-%d").build());
}
MediaType.java 文件源码
项目:googles-monorepo-demo
阅读 32
收藏 0
点赞 0
评论 0
private String computeToString() {
StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
if (!parameters.isEmpty()) {
builder.append("; ");
Multimap<String, String> quotedParameters =
Multimaps.transformValues(
parameters,
new Function<String, String>() {
@Override
public String apply(String value) {
return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
}
});
PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
}
return builder.toString();
}
RemoteConfigLongPollService.java 文件源码
项目:apollo-custom
阅读 26
收藏 0
点赞 0
评论 0
/**
* Constructor.
*/
public RemoteConfigLongPollService() {
m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second
m_longPollingStopped = new AtomicBoolean(false);
m_longPollingService = Executors.newSingleThreadExecutor(
ApolloThreadFactory.create("RemoteConfigLongPollService", true));
m_longPollStarted = new AtomicBoolean(false);
m_longPollNamespaces =
Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create());
m_notifications = Maps.newConcurrentMap();
m_remoteNotificationMessages = Maps.newConcurrentMap();
m_responseType = new TypeToken<List<ApolloConfigNotification>>() {
}.getType();
gson = new Gson();
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS());
}
DOMNotificationRouter.java 文件源码
项目:hashsdn-controller
阅读 42
收藏 0
点赞 0
评论 0
@Override
public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final Collection<SchemaPath> types) {
final ListenerRegistration<T> reg = new AbstractListenerRegistration<T>(listener) {
@Override
protected void removeRegistration() {
final ListenerRegistration<T> me = this;
synchronized (DOMNotificationRouter.this) {
replaceListeners(ImmutableMultimap.copyOf(Multimaps.filterValues(listeners, input -> input != me)));
}
}
};
if (!types.isEmpty()) {
final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap.builder();
b.putAll(listeners);
for (final SchemaPath t : types) {
b.put(t, reg);
}
replaceListeners(b.build());
}
return reg;
}
Maintenance.java 文件源码
项目:Mastering-Mesos
阅读 37
收藏 0
点赞 0
评论 0
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getHosts() {
return storage.read(storeProvider -> {
Multimap<MaintenanceMode, String> hostsByMode =
Multimaps.transformValues(
Multimaps.index(
storeProvider.getAttributeStore().getHostAttributes(),
IHostAttributes::getMode),
IHostAttributes::getHost);
Map<MaintenanceMode, Object> hosts = ImmutableMap.of(
DRAINED, ImmutableSet.copyOf(hostsByMode.get(DRAINED)),
SCHEDULED, ImmutableSet.copyOf(hostsByMode.get(SCHEDULED)),
DRAINING, getTasksByHosts(storeProvider, hostsByMode.get(DRAINING)).asMap());
return Response.ok(hosts).build();
});
}
SchedulerThriftInterface.java 文件源码
项目:Mastering-Mesos
阅读 26
收藏 0
点赞 0
评论 0
private static Set<InstanceTaskConfig> buildInitialState(Map<Integer, ITaskConfig> tasks) {
// Translate tasks into instance IDs.
Multimap<ITaskConfig, Integer> instancesByConfig = HashMultimap.create();
Multimaps.invertFrom(Multimaps.forMap(tasks), instancesByConfig);
// Reduce instance IDs into contiguous ranges.
Map<ITaskConfig, Set<Range<Integer>>> rangesByConfig =
Maps.transformValues(instancesByConfig.asMap(), Numbers::toRanges);
ImmutableSet.Builder<InstanceTaskConfig> builder = ImmutableSet.builder();
for (Map.Entry<ITaskConfig, Set<Range<Integer>>> entry : rangesByConfig.entrySet()) {
builder.add(new InstanceTaskConfig()
.setTask(entry.getKey().newBuilder())
.setInstances(IRange.toBuildersSet(convertRanges(entry.getValue()))));
}
return builder.build();
}
ReadOnlySchedulerImpl.java 文件源码
项目:Mastering-Mesos
阅读 29
收藏 0
点赞 0
评论 0
@Override
public Response getRoleSummary() {
Multimap<String, IJobKey> jobsByRole = storage.read(
storeProvider ->
Multimaps.index(storeProvider.getTaskStore().getJobKeys(), IJobKey::getRole));
Multimap<String, IJobKey> cronJobsByRole = Multimaps.index(
Iterables.transform(Storage.Util.fetchCronJobs(storage), IJobConfiguration::getKey),
IJobKey::getRole);
Set<RoleSummary> summaries = FluentIterable.from(
Sets.union(jobsByRole.keySet(), cronJobsByRole.keySet()))
.transform(role -> new RoleSummary(
role,
jobsByRole.get(role).size(),
cronJobsByRole.get(role).size()))
.toSet();
return ok(Result.roleSummaryResult(new RoleSummaryResult(summaries)));
}
RemoteConfigLongPollService.java 文件源码
项目:apollo
阅读 53
收藏 0
点赞 0
评论 0
/**
* Constructor.
*/
public RemoteConfigLongPollService() {
m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second
m_longPollingStopped = new AtomicBoolean(false);
m_longPollingService = Executors.newSingleThreadExecutor(
ApolloThreadFactory.create("RemoteConfigLongPollService", true));
m_longPollStarted = new AtomicBoolean(false);
m_longPollNamespaces =
Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create());
m_notifications = Maps.newConcurrentMap();
m_remoteNotificationMessages = Maps.newConcurrentMap();
m_responseType = new TypeToken<List<ApolloConfigNotification>>() {
}.getType();
gson = new Gson();
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS());
}
LoadStructuralVariants.java 文件源码
项目:hmftools
阅读 28
收藏 0
点赞 0
评论 0
@NotNull
private static List<EnrichedStructuralVariant> enrichStructuralVariants(@NotNull List<StructuralVariant> variants,
@NotNull DatabaseAccess dbAccess, @NotNull String tumorSample) {
final PurityContext purityContext = dbAccess.readPurityContext(tumorSample);
if (purityContext == null) {
LOGGER.warn("Unable to retrieve purple data. Enrichment may be incomplete.");
}
final PurityAdjuster purityAdjuster = purityContext == null
? new PurityAdjuster(Gender.FEMALE, 1, 1)
: new PurityAdjuster(purityContext.gender(), purityContext.bestFit().purity(), purityContext.bestFit().normFactor());
final List<PurpleCopyNumber> copyNumberList = dbAccess.readCopynumbers(tumorSample);
final Multimap<String, PurpleCopyNumber> copyNumbers = Multimaps.index(copyNumberList, PurpleCopyNumber::chromosome);
return EnrichedStructuralVariantFactory.enrich(variants, purityAdjuster, copyNumbers);
}
JsonConfigWriter.java 文件源码
项目:endpoints-java
阅读 26
收藏 0
点赞 0
评论 0
@Override
public Map<ApiKey, String> writeConfig(Iterable<? extends ApiConfig> configs)
throws ApiConfigException {
Multimap<ApiKey, ? extends ApiConfig> apisByKey = Multimaps.index(configs,
new Function<ApiConfig, ApiKey>() {
@Override public ApiKey apply(ApiConfig config) {
return config.getApiKey();
}
});
// This *must* retain the order of apisByKey so the lily_java_api BUILD rule has predictable
// output order.
Map<ApiKey, String> results = Maps.newLinkedHashMap();
for (ApiKey apiKey : apisByKey.keySet()) {
Collection<? extends ApiConfig> apiConfigs = apisByKey.get(apiKey);
validator.validate(apiConfigs);
results.put(apiKey, generateForApi(apiConfigs));
}
return results;
}
AstyanaxBlockedDataReaderDAO.java 文件源码
项目:emodb
阅读 32
收藏 0
点赞 0
评论 0
/**
* Gets the topology for a Cassandra keyspace as a Multimap, where the keys identify a rack (or availability zone
* in Amazon) and the values are the token ranges for each host in that rack. For example, for a well distributed
* ring of 12 hosts and a replication factor of 3 this method would return a Multimap with 3 keys and each key would
* contain 4 token ranges.
*/
private Multimap<String, TokenRange> describeCassandraTopology(final Keyspace keyspace) {
try {
@SuppressWarnings ("unchecked")
ConnectionPool<Cassandra.Client> connectionPool = (ConnectionPool<Cassandra.Client>) keyspace.getConnectionPool();
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Multimap<String, TokenRange>>(EmptyKeyspaceTracerFactory.getInstance().newTracer(CassandraOperationType.DESCRIBE_RING), keyspace.getKeyspaceName()) {
@Override
protected Multimap<String, TokenRange> internalExecute(Cassandra.Client client, ConnectionContext state)
throws Exception {
Multimap<String, TokenRange> racks = ArrayListMultimap.create();
for (org.apache.cassandra.thrift.TokenRange tokenRange : client.describe_local_ring(getKeyspace())) {
// The final local endpoint "owns" the token range, the rest are for replication
EndpointDetails endpointDetails = Iterables.getLast(tokenRange.getEndpoint_details());
racks.put(endpointDetails.getRack(),
new TokenRangeImpl(tokenRange.getStart_token(), tokenRange.getEnd_token(), tokenRange.getEndpoints()));
}
return Multimaps.unmodifiableMultimap(racks);
}
},
keyspace.getConfig().getRetryPolicy().duplicate()).getResult();
} catch (ConnectionException e) {
throw Throwables.propagate(e);
}
}
AstyanaxDataReaderDAO.java 文件源码
项目:emodb
阅读 29
收藏 0
点赞 0
评论 0
/**
* Gets the topology for a Cassandra keyspace as a Multimap, where the keys identify a rack (or availability zone
* in Amazon) and the values are the token ranges for each host in that rack. For example, for a well distributed
* ring of 12 hosts and a replication factor of 3 this method would return a Multimap with 3 keys and each key would
* contain 4 token ranges.
*/
private Multimap<String, TokenRange> describeCassandraTopology(final Keyspace keyspace) {
try {
@SuppressWarnings ("unchecked")
ConnectionPool<Cassandra.Client> connectionPool = (ConnectionPool<Cassandra.Client>) keyspace.getConnectionPool();
return connectionPool.executeWithFailover(
new AbstractKeyspaceOperationImpl<Multimap<String, TokenRange>>(EmptyKeyspaceTracerFactory.getInstance().newTracer(CassandraOperationType.DESCRIBE_RING), keyspace.getKeyspaceName()) {
@Override
protected Multimap<String, TokenRange> internalExecute(Cassandra.Client client, ConnectionContext state)
throws Exception {
Multimap<String, TokenRange> racks = ArrayListMultimap.create();
for (org.apache.cassandra.thrift.TokenRange tokenRange : client.describe_local_ring(getKeyspace())) {
// The final local endpoint "owns" the token range, the rest are for replication
EndpointDetails endpointDetails = Iterables.getLast(tokenRange.getEndpoint_details());
racks.put(endpointDetails.getRack(),
new TokenRangeImpl(tokenRange.getStart_token(), tokenRange.getEnd_token(), tokenRange.getEndpoints()));
}
return Multimaps.unmodifiableMultimap(racks);
}
},
keyspace.getConfig().getRetryPolicy().duplicate()).getResult();
} catch (ConnectionException e) {
throw Throwables.propagate(e);
}
}
MediaType.java 文件源码
项目:codebuff
阅读 30
收藏 0
点赞 0
评论 0
private String computeToString() {
StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
if (!parameters.isEmpty()) {
builder.append("; ");
Multimap<String, String> quotedParameters =
Multimaps.transformValues(
parameters,
new Function<String, String>() {
@Override
public String apply(String value) {
return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
}
});
PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
}
return builder.toString();
}
ApiSurface.java 文件源码
项目:beam
阅读 26
收藏 0
点赞 0
评论 0
/** See {@link #getExposedToExposers}. */
private void constructExposedToExposers() {
visited = Sets.newHashSet();
exposedToExposers =
Multimaps.newSetMultimap(
Maps.<Class<?>, Collection<Class<?>>>newHashMap(),
new Supplier<Set<Class<?>>>() {
@Override
public Set<Class<?>> get() {
return Sets.newHashSet();
}
});
for (Class<?> clazz : rootClasses) {
addExposedTypes(clazz, null);
}
}
Validator.java 文件源码
项目:xtext-core
阅读 38
收藏 0
点赞 0
评论 0
protected Multimap<URI, MWEDiagnostic> groupByURI(MWEDiagnostic[] diagnostic) {
Multimap<URI, MWEDiagnostic> result = Multimaps.newMultimap(
Maps.<URI, Collection<MWEDiagnostic>> newLinkedHashMap(), new Supplier<Collection<MWEDiagnostic>>() {
@Override
public Collection<MWEDiagnostic> get() {
return Sets.newTreeSet(getDiagnosticComparator());
}
});
result.putAll(Multimaps.index(Arrays.asList(diagnostic), new Function<MWEDiagnostic, URI>() {
@Override
public URI apply(MWEDiagnostic from) {
Issue issue = (Issue) from.getElement();
URI uriToProblem = issue.getUriToProblem();
return uriToProblem != null ? uriToProblem.trimFragment() : NullURI;
}
}));
return result;
}
CheckJavaValidator.java 文件源码
项目:dsl-devkit
阅读 27
收藏 0
点赞 0
评论 0
/**
* Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T
* to a string which is used for checking for duplicates.
*
* @param <T>
* the generic type
* @param predicate
* the predicate acting as a guard
* @param function
* returns a string for an instance of type T
* @param elements
* the elements to be checked
* @return the duplicates
*/
private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) {
List<T> result = Lists.newArrayList();
Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() {
@Override
public Collection<T> get() {
return Lists.<T> newArrayList();
}
});
for (final T candidate : elements) {
if (predicate.apply(candidate)) {
multiMap.put(function.apply(candidate), candidate);
}
}
for (String elem : multiMap.keySet()) {
final Collection<T> duplicates = multiMap.get(elem);
if (duplicates.size() > 1) {
result.addAll(duplicates);
}
}
return result;
}
CheckCfgJavaValidator.java 文件源码
项目:dsl-devkit
阅读 24
收藏 0
点赞 0
评论 0
/**
* Gets duplicates of a given type based on a guard (predicate). A given function is used for converting an instance of type T
* to a string which is used for checking for duplicates.
*
* @param <T>
* the generic type
* @param predicate
* the predicate acting as a guard
* @param function
* returns a string for an instance of type T
* @param elements
* the elements to be checked
* @return the duplicates
*/
private <T extends EObject> Iterable<T> getDuplicates(final Predicate<T> predicate, final Function<T, String> function, final Iterable<T> elements) {
List<T> result = Lists.newArrayList();
Multimap<String, T> multiMap = Multimaps.newMultimap(Maps.<String, Collection<T>> newHashMap(), new Supplier<Collection<T>>() {
@Override
public Collection<T> get() {
return Lists.<T> newArrayList();
}
});
for (final T candidate : elements) {
if (predicate.apply(candidate)) {
multiMap.put(function.apply(candidate), candidate);
}
}
for (String elem : multiMap.keySet()) {
final Collection<T> duplicates = multiMap.get(elem);
if (duplicates.size() > 1) {
result.addAll(duplicates);
}
}
return result;
}
ChangesetServiceImpl.java 文件源码
项目:jira-dvcs-connector
阅读 23
收藏 0
点赞 0
评论 0
@Override
public List<Changeset> getChangesetsWithFileDetails(List<Changeset> changesets)
{
ImmutableList.Builder<Changeset> detailedChangesets = ImmutableList.builder();
// group by repo so we only have to load each repo one time inside the loop
ListMultimap<Integer, Changeset> changesetsByRepo = Multimaps.index(changesets, Changesets.TO_REPOSITORY_ID);
for (Map.Entry<Integer, Collection<Changeset>> repoChangesets : changesetsByRepo.asMap().entrySet())
{
final Repository repository = repositoryDao.get(repoChangesets.getKey());
final DvcsCommunicator communicator = dvcsCommunicatorProvider.getCommunicator(repository.getDvcsType());
processRepository(repository, repoChangesets.getValue(), communicator, detailedChangesets);
}
return detailedChangesets.build();
}
ListMultimapProperty.java 文件源码
项目:FreeBuilder
阅读 30
收藏 0
点赞 0
评论 0
private void addGetter(SourceBuilder code, Metadata metadata) {
code.addLine("")
.addLine("/**")
.addLine(" * Returns an unmodifiable view of the multimap that will be returned by")
.addLine(" * %s.", metadata.getType().javadocNoArgMethodLink(property.getGetterName()))
.addLine(" * Changes to this builder will be reflected in the view.")
.addLine(" */")
.addLine("public %s<%s, %s> %s() {",
ListMultimap.class,
keyType,
valueType,
getter(property))
.addLine(" return %s.unmodifiableListMultimap(%s);",
Multimaps.class, property.getField())
.addLine("}");
}
SetMultimapProperty.java 文件源码
项目:FreeBuilder
阅读 24
收藏 0
点赞 0
评论 0
private void addGetter(SourceBuilder code, Metadata metadata) {
code.addLine("")
.addLine("/**")
.addLine(" * Returns an unmodifiable view of the multimap that will be returned by")
.addLine(" * %s.", metadata.getType().javadocNoArgMethodLink(property.getGetterName()))
.addLine(" * Changes to this builder will be reflected in the view.")
.addLine(" */")
.addLine("public %s<%s, %s> %s() {",
SetMultimap.class,
keyType,
valueType,
getter(property))
.addLine(" return %s.unmodifiableSetMultimap(%s);",
Multimaps.class, property.getField())
.addLine("}");
}
ListMultimapMutateMethodTest.java 文件源码
项目:FreeBuilder
阅读 24
收藏 0
点赞 0
评论 0
@Test
public void mutateAndAddAtIndexViaAsMapModifiesUnderlyingProperty() {
behaviorTester
.with(new Processor(features))
.with(CHECKED_PROPERTY)
.with(testBuilder()
.addLine("DataType value = new DataType.Builder()")
.addLine(" .putAllItems(\"one\", ImmutableList.of(\"A\", \"B\", \"C\"))")
.addLine(" .mutateItems(items -> %s.asMap(items).get(\"one\").add(2, \"foo\"))",
Multimaps.class)
.addLine(" .build();")
.addLine("assertThat(value.getItems())")
.addLine(" .contains(\"one\", \"A\", \"B\", \"foo\", \"C\")")
.addLine(" .andNothingElse()")
.addLine(" .inOrder();")
.build())
.runTest();
}
ListMultimapMutateMethodTest.java 文件源码
项目:FreeBuilder
阅读 27
收藏 0
点赞 0
评论 0
@Test
public void mutateAndAddAtIndexViaAsMapKeepsSubstitute() {
behaviorTester
.with(new Processor(features))
.with(INTERNED_PROPERTY)
.with(testBuilder()
.addLine("String s = new String(\"foobar\");")
.addLine("String i = s.intern();")
.addLine("assertThat(s).isNotSameAs(i);")
.addLine("DataType value = new DataType.Builder()")
.addLine(" .putAllItems(\"one\", ImmutableList.of(\"A\", \"B\", \"C\"))")
.addLine(" .mutateItems(items -> %s.asMap(items).get(\"one\").add(2, s))",
Multimaps.class)
.addLine(" .build();")
.addLine("assertThat(value.getItems().get(\"one\").get(2)).isSameAs(i);")
.build())
.runTest();
}