List of usage examples for com.google.common.collect ListMultimap get
@Override List<V> get(@Nullable K key);
Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.
From source file:org.sonar.server.component.ws.SuggestionsAction.java
/** * we are generating suggestions, by using (1) favorites and (2) recently browsed components (without searchin in Elasticsearch) *//*from w w w . ja va 2s .c o m*/ private SuggestionsWsResponse loadSuggestionsWithoutSearch(int skip, int limit, Set<String> recentlyBrowsedKeys, List<String> qualifiers) { List<ComponentDto> favoriteDtos = favoriteFinder.list(); if (favoriteDtos.isEmpty() && recentlyBrowsedKeys.isEmpty()) { return newBuilder().build(); } try (DbSession dbSession = dbClient.openSession(false)) { Set<ComponentDto> componentDtos = new HashSet<>(favoriteDtos); if (!recentlyBrowsedKeys.isEmpty()) { componentDtos.addAll(dbClient.componentDao().selectByKeys(dbSession, recentlyBrowsedKeys)); } List<ComponentDto> authorizedComponents = userSession.keepAuthorizedComponents(USER, componentDtos); ListMultimap<String, ComponentDto> componentsPerQualifier = authorizedComponents.stream() .collect(MoreCollectors.index(ComponentDto::qualifier)); if (componentsPerQualifier.isEmpty()) { return newBuilder().build(); } Set<String> favoriteUuids = favoriteDtos.stream().map(ComponentDto::uuid) .collect(MoreCollectors.toSet(favoriteDtos.size())); Comparator<ComponentDto> favoriteComparator = Comparator .comparing(c -> favoriteUuids.contains(c.uuid()) ? -1 : +1); Comparator<ComponentDto> comparator = favoriteComparator.thenComparing(ComponentDto::name); ComponentIndexResults componentsPerQualifiers = ComponentIndexResults.newBuilder() .setQualifiers(qualifiers.stream().map(q -> { List<ComponentDto> componentsOfThisQualifier = componentsPerQualifier.get(q); List<ComponentHit> hits = componentsOfThisQualifier.stream().sorted(comparator).skip(skip) .limit(limit).map(ComponentDto::uuid).map(ComponentHit::new) .collect(MoreCollectors.toList(limit)); int totalHits = componentsOfThisQualifier.size(); return new ComponentHitsPerQualifier(q, hits, totalHits); })).build(); return buildResponse(recentlyBrowsedKeys, favoriteUuids, componentsPerQualifiers, dbSession, authorizedComponents, skip + limit).build(); } }
From source file:fr.inria.atlanmod.instantiator.SpecimenGenerator.java
/** * @param eObject// w w w .ja va 2 s . c om * @param indexByKind */ private void generateCrossReferences(EObject eObject, ListMultimap<EClass, EObject> indexByKind) { Iterable<EReference> eAllNonContainment = ePackagesData.eAllNonContainment(eObject.eClass()); for (EReference eReference : eAllNonContainment) { EClass eReferenceType = eReference.getEReferenceType(); UniformLongDistribution distribution = c.getDistributionFor(eReference); if (eReference.isMany()) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>) eObject.eGet(eReference); long sample; do { sample = distribution.sample(); } while (sample < eReference.getLowerBound()); for (int i = 0; i < sample; i++) { List<EObject> possibleValues = indexByKind.get(eReferenceType); if (!possibleValues.isEmpty()) { final EObject nextEObject = possibleValues.get(generator.nextInt(possibleValues.size())); values.add(nextEObject); } } } else { if (eReference.getLowerBound() != 0 || booleanInDistribution(distribution)) {// eReference.getLowerBound() // == // 1 List<EObject> possibleValues = indexByKind.get(eReferenceType); if (!possibleValues.isEmpty()) { final EObject nextEObject = possibleValues.get(generator.nextInt(possibleValues.size())); eObject.eSet(eReference, nextEObject); } } } } }
From source file:com.google.gerrit.server.plugins.PluginGuiceEnvironment.java
private void reattachMap(ListMultimap<TypeLiteral<?>, ReloadableRegistrationHandle<?>> oldHandles, Map<TypeLiteral<?>, DynamicMap<?>> maps, @Nullable Injector src, Plugin newPlugin) { if (src == null || maps == null || maps.isEmpty()) { return;/* w w w. ja va 2s. co m*/ } for (Map.Entry<TypeLiteral<?>, DynamicMap<?>> e : maps.entrySet()) { @SuppressWarnings("unchecked") TypeLiteral<Object> type = (TypeLiteral<Object>) e.getKey(); @SuppressWarnings("unchecked") PrivateInternals_DynamicMapImpl<Object> map = (PrivateInternals_DynamicMapImpl<Object>) e.getValue(); Map<Annotation, ReloadableRegistrationHandle<?>> am = Maps.newHashMap(); for (ReloadableRegistrationHandle<?> h : oldHandles.get(type)) { Annotation a = h.getKey().getAnnotation(); if (a != null && !UNIQUE_ANNOTATION.isInstance(a)) { am.put(a, h); } } for (Binding<?> binding : bindings(src, e.getKey())) { @SuppressWarnings("unchecked") Binding<Object> b = (Binding<Object>) binding; Key<Object> key = b.getKey(); if (key.getAnnotation() == null) { continue; } @SuppressWarnings("unchecked") ReloadableRegistrationHandle<Object> h = (ReloadableRegistrationHandle<Object>) am .remove(key.getAnnotation()); if (h != null) { replace(newPlugin, h, b); oldHandles.remove(type, h); } else { newPlugin.add(map.put(newPlugin.getName(), b.getKey(), b.getProvider())); } } } }
From source file:eu.esdihumboldt.hale.ui.functions.core.MergeParameterPage.java
/** * @see eu.esdihumboldt.hale.ui.function.generic.pages.ParameterPage#setParameter(java.util.Set, * com.google.common.collect.ListMultimap) *///from w w w . ja va 2 s. c om @Override public void setParameter(Set<FunctionParameterDefinition> params, ListMultimap<String, ParameterValue> initialValues) { if (params.size() > 1) throw new IllegalArgumentException("MergeParameterPage is only for one parameter"); parameter = params.iterator().next(); if (parameter.getName().equals(PARAMETER_PROPERTY)) { setTitle("Please select the properties that have to match"); setDescription("Instances that have equal values for these properties will be merged into one"); } else if (parameter.getName().equals(PARAMETER_ADDITIONAL_PROPERTY)) { setTitle("Please select other equal properties to merge"); setDescription("For these properties only the unique values will be retained in the merged instance"); } else throw new IllegalArgumentException( "MergeParameterPage is only for property or additional_property parameters"); if (initialValues != null) { // cell gets edited List<ParameterValue> tmp = initialValues.get(parameter.getName()); if (tmp != null) { initialSelection = new ArrayList<String>(tmp.size()); for (ParameterValue value : tmp) { // TODO use MergeUtil helper function instead // XXX needs selection to be QName based initialSelection.add(value.as(String.class)); } } else { initialSelection = Collections.emptyList(); } setPageComplete(true); } }
From source file:edu.cmu.cs.lti.ark.fn.parsing.LocalFeatureReading.java
private List<FrameFeatures> parseSpanLines(List<String> spanLines, List<String> frameLines) { final Pair<List<String>, List<List<SpanAndCorrespondingFeatures>>> feLinesAndSpanLines = readFeLinesAndSpans( spanLines);//from w ww . j av a2 s .c o m final List<String> feLines = feLinesAndSpanLines.first; final List<List<SpanAndCorrespondingFeatures>> spansList = feLinesAndSpanLines.second; // group by sentence idx // map from sentence idx to list of feLines/parseLines idxs for that sentence final ListMultimap<Integer, Integer> frameIndexMap = ArrayListMultimap.create(); for (int i = 0; i < feLines.size(); i++) { final String[] fields = feLines.get(i).split("\t"); final int sentenceIdx = Integer.parseInt(fields[fields.length - 1]); frameIndexMap.put(sentenceIdx, i); } // zip up into list of FrameFeatures' final List<FrameFeatures> frameFeaturesList = Lists.newArrayList(); for (int i = 0; i < frameLines.size(); i++) { final String[] fields = frameLines.get(i).split("\t"); // throw away the first two fields (rank and score) // hack around the fact that parsing this goddamn file format is hardcoded in 20 different places final List<String> tokens = Arrays.asList(fields).subList(2, fields.length); final String frame = tokens.get(1).trim(); final String[] span = tokens.get(3).split("_"); int targetStartTokenIdx = parseInt(span[0]); int targetEndTokenIdx = parseInt(span[span.length - 1]); final List<Integer> feLineIdxs = frameIndexMap.get(i); final List<String> fElements = Lists.newArrayList(); final List<SpanAndCorrespondingFeatures[]> fElementSpansAndFeatures = Lists.newArrayList(); for (int feLineIdx : feLineIdxs) { fElements.add(feLines.get(feLineIdx).split("\t")[1]); final List<SpanAndCorrespondingFeatures> spans = spansList.get(feLineIdx); fElementSpansAndFeatures.add(spans.toArray(new SpanAndCorrespondingFeatures[spans.size()])); } final FrameFeatures frameFeatures = new FrameFeatures(frame, targetStartTokenIdx, targetEndTokenIdx, fElements, fElementSpansAndFeatures); frameFeaturesList.add(frameFeatures); } return frameFeaturesList; }
From source file:org.atteo.config.xmlmerge.XmlCombiner.java
private Context combine(Context recessive, Context dominant) { CombineSelf dominantCombineSelf = getCombineSelf(dominant.getElement()); CombineSelf recessiveCombineSelf = getCombineSelf(recessive.getElement()); if (dominantCombineSelf == CombineSelf.REMOVE) { return null; } else if (dominantCombineSelf == CombineSelf.OVERRIDE || (recessiveCombineSelf == CombineSelf.OVERRIDABLE)) { Context result = copyRecursively(dominant); result.getElement().removeAttribute(CombineSelf.ATTRIBUTE_NAME); return result; }//from w w w . j a v a2 s .c om CombineChildren combineChildren = getCombineChildren(dominant.getElement()); if (combineChildren == null) { combineChildren = getCombineChildren(recessive.getElement()); if (combineChildren == null) { combineChildren = CombineChildren.MERGE; } } if (combineChildren == CombineChildren.APPEND) { if (recessive.getElement() != null) { removeWhitespaceTail(recessive.getElement()); appendRecursively(dominant, recessive); return recessive; } else { return copyRecursively(dominant); } } Element resultElement = document.createElement(dominant.getElement().getTagName()); copyAttributes(recessive.getElement(), resultElement); copyAttributes(dominant.getElement(), resultElement); // when dominant combineSelf is null or DEFAULTS use combineSelf from recessive CombineSelf combineSelf = dominantCombineSelf; if ((combineSelf == null && recessiveCombineSelf != CombineSelf.DEFAULTS)) { //|| (combineSelf == CombineSelf.DEFAULTS && recessive.getElement() != null)) { combineSelf = recessiveCombineSelf; } if (combineSelf != null) { resultElement.setAttribute(CombineSelf.ATTRIBUTE_NAME, combineSelf.name()); } else { resultElement.removeAttribute(CombineSelf.ATTRIBUTE_NAME); } ListMultimap<Key, Context> recessiveContexts = recessive.mapChildContexts(); ListMultimap<Key, Context> dominantContexts = dominant.mapChildContexts(); Set<String> tagNamesInDominant = getTagNames(dominantContexts); // Execute only if there is at least one subelement in recessive if (!recessiveContexts.isEmpty()) { for (Entry<Key, Context> entry : recessiveContexts.entries()) { Key key = entry.getKey(); Context recessiveContext = entry.getValue(); if (key == Key.BEFORE_END) { continue; } if (getCombineSelf(recessiveContext.getElement()) == CombineSelf.OVERRIDABLE_BY_TAG) { if (!tagNamesInDominant.contains(key.getName())) { recessiveContext.addAsChildTo(resultElement); } continue; } if (dominantContexts.get(key).size() == 1 && recessiveContexts.get(key).size() == 1) { Context dominantContext = dominantContexts.get(key).iterator().next(); Context combined = combine(recessiveContext, dominantContext); if (combined != null) { combined.addAsChildTo(resultElement); } } else { recessiveContext.addAsChildTo(resultElement); } } } for (Entry<Key, Context> entry : dominantContexts.entries()) { Key key = entry.getKey(); Context dominantContext = entry.getValue(); if (key == Key.BEFORE_END) { dominantContext.addAsChildTo(resultElement, document); // break? this should be the last anyway... continue; } List<Context> associatedRecessives = recessiveContexts.get(key); if (dominantContexts.get(key).size() == 1 && associatedRecessives.size() == 1 && getCombineSelf(associatedRecessives.get(0).getElement()) != CombineSelf.OVERRIDABLE_BY_TAG) { // already added } else { Context combined = combine(Context.fromElement(null), dominantContext); if (combined != null) { combined.addAsChildTo(resultElement); } } } Context result = new Context(); result.setElement(resultElement); appendNeighbours(dominant, result); return result; }
From source file:com.android.ide.common.res2.DataMerger.java
/** * Sets the post blob load state to WRITTEN. * * After a load from the blob file, all items have their state set to nothing. * If the load mode is set to incrementalState then we want the items that are in the current * merge result to have their state be WRITTEN. * * This will allow further updates with {@link #mergeData(MergeConsumer, boolean)} to ignore the * state at load time and only apply the new changes. * * @see #loadFromBlob(java.io.File, boolean) * @see DataItem#isWritten()/* www .j av a 2 s .c o m*/ */ private void setPostBlobLoadStateToWritten() { ListMultimap<String, I> itemMap = ArrayListMultimap.create(); // put all the sets into list per keys. The order is important as the lower sets are // overridden by the higher sets. for (S dataSet : mDataSets) { ListMultimap<String, I> map = dataSet.getDataMap(); for (Map.Entry<String, Collection<I>> entry : map.asMap().entrySet()) { itemMap.putAll(entry.getKey(), entry.getValue()); } } // the items that represent the current state is the last item in the list for each key. for (String key : itemMap.keySet()) { List<I> itemList = itemMap.get(key); itemList.get(itemList.size() - 1).resetStatusToWritten(); } }
From source file:com.android.ide.common.res2.DataMerger.java
/** * Sets the post blob load state to TOUCHED. * * After a load from the blob file, all items have their state set to nothing. * If the load mode is not set to incrementalState then we want the items that are in the * current merge result to have their state be TOUCHED. * * This will allow the first use of {@link #mergeData(MergeConsumer, boolean)} to add these * to the consumer as if they were new items. * * @see #loadFromBlob(java.io.File, boolean) * @see DataItem#isTouched()//from w w w.j a va2 s . c o m */ private void setPostBlobLoadStateToTouched() { ListMultimap<String, I> itemMap = ArrayListMultimap.create(); // put all the sets into list per keys. The order is important as the lower sets are // overridden by the higher sets. for (S dataSet : mDataSets) { ListMultimap<String, I> map = dataSet.getDataMap(); for (Map.Entry<String, Collection<I>> entry : map.asMap().entrySet()) { itemMap.putAll(entry.getKey(), entry.getValue()); } } // the items that represent the current state is the last item in the list for each key. for (String key : itemMap.keySet()) { List<I> itemList = itemMap.get(key); itemList.get(itemList.size() - 1).resetStatusToTouched(); } }
From source file:com.google.javascript.jscomp.JSModuleGraph.java
/** * Apply the dependency options to the list of sources, returning a new * source list re-ordering and dropping files as necessary. * This module graph will be updated to reflect the new list. * * @param inputs The original list of sources. Used to ensure that the sort * is stable.//from w ww . ja v a2 s. c o m * @throws CircularDependencyException if there is a circular dependency * between the provides and requires. * @throws MissingProvideException if an entry point was not provided * by any of the inputs. * @see DependencyOptions for more info on how this works. */ public List<CompilerInput> manageDependencies(DependencyOptions depOptions, List<CompilerInput> inputs) throws CircularDependencyException, MissingProvideException, MissingModuleException { SortedDependencies<CompilerInput> sorter = new SortedDependencies<>(inputs); Iterable<CompilerInput> entryPointInputs = createEntryPointInputs(depOptions, inputs, sorter); // The order of inputs, sorted independently of modules. List<CompilerInput> absoluteOrder = sorter.getDependenciesOf(inputs, depOptions.shouldSortDependencies()); // Figure out which sources *must* be in each module. ListMultimap<JSModule, CompilerInput> entryPointInputsPerModule = LinkedListMultimap.create(); for (CompilerInput input : entryPointInputs) { JSModule module = input.getModule(); Preconditions.checkNotNull(module); entryPointInputsPerModule.put(module, input); } // Clear the modules of their inputs. This also nulls out // the input's reference to its module. for (JSModule module : getAllModules()) { module.removeAll(); } // Figure out which sources *must* be in each module, or in one // of that module's dependencies. for (JSModule module : entryPointInputsPerModule.keySet()) { List<CompilerInput> transitiveClosure = sorter.getDependenciesOf(entryPointInputsPerModule.get(module), depOptions.shouldSortDependencies()); for (CompilerInput input : transitiveClosure) { JSModule oldModule = input.getModule(); if (oldModule == null) { input.setModule(module); } else { input.setModule(null); input.setModule(getDeepestCommonDependencyInclusive(oldModule, module)); } } } // All the inputs are pointing to the modules that own them. Yeah! // Update the modules to reflect this. for (CompilerInput input : absoluteOrder) { JSModule module = input.getModule(); if (module != null) { module.add(input); } } // Now, generate the sorted result. ImmutableList.Builder<CompilerInput> result = ImmutableList.builder(); for (JSModule module : getAllModules()) { result.addAll(module.getInputs()); } return result.build(); }
From source file:org.terasology.assets.module.ModuleAwareAssetTypeManager.java
@SuppressWarnings("unchecked") private <T extends Asset<U>, U extends AssetData> void prepareAssetType(AssetType<T, U> assetType, Collection<String> folderNames, ResolutionStrategy resolutionStrategy, ModuleEnvironment environment, ListMultimap<Class<? extends AssetData>, AssetFileFormat<?>> extensionFileFormats, ListMultimap<Class<? extends AssetData>, AssetAlterationFileFormat<?>> extensionSupplementalFormats, ListMultimap<Class<? extends AssetData>, AssetAlterationFileFormat<?>> extensionDeltaFormats) { assetType.setResolutionStrategy(resolutionStrategy); for (AssetDataProducer producer : coreProducers.get(assetType.getAssetClass())) { assetType.addProducer(producer); }//from www . ja va2 s . co m if (!folderNames.isEmpty()) { List<AssetFileFormat<?>> assetFormats = Lists.newArrayList(coreFormats.get(assetType.getAssetClass())); assetFormats.addAll(extensionFileFormats.get(assetType.getAssetDataClass())); List<AssetAlterationFileFormat<?>> supplementalFormats = Lists .newArrayList(coreSupplementalFormats.get(assetType.getAssetClass())); supplementalFormats.addAll(extensionSupplementalFormats.get(assetType.getAssetDataClass())); List<AssetAlterationFileFormat<?>> deltaFormats = Lists .newArrayList(coreDeltaFormats.get(assetType.getAssetClass())); deltaFormats.addAll(extensionDeltaFormats.get(assetType.getAssetDataClass())); ModuleAssetDataProducer moduleProducer = new ModuleAssetDataProducer(environment, assetFormats, supplementalFormats, deltaFormats, folderNames); assetType.addProducer(moduleProducer); subscribeToChanges(assetType, moduleProducer, folderNames); } }