Example usage for com.google.common.collect Multimap asMap

List of usage examples for com.google.common.collect Multimap asMap

Introduction

In this page you can find the example usage for com.google.common.collect Multimap asMap.

Prototype

Map<K, Collection<V>> asMap();

Source Link

Document

Returns a view of this multimap as a Map from each distinct key to the nonempty collection of that key's associated values.

Usage

From source file:co.cask.cdap.data2.metadata.lineage.LineageCollapser.java

/**
 * Collapse {@link Relation}s based on {@link CollapseType}
 * @param relations lineage relations/*w w  w. ja v a  2  s . co  m*/
 * @param collapseTypes fields to collapse relations on
 * @return collapsed relations
 */
public static Set<CollapsedRelation> collapseRelations(Iterable<Relation> relations,
        Set<CollapseType> collapseTypes) {
    Set<CollapsedRelation> collapsedRelations = new HashSet<>();

    Multimap<CollapseKey, Relation> multimap = HashMultimap.create();
    for (Relation relation : relations) {
        multimap.put(getCollapseKey(relation, collapseTypes), relation);
    }
    LOG.trace("Collapsed relations: {}", multimap.asMap());

    for (Map.Entry<CollapseKey, Collection<Relation>> collapsedEntry : multimap.asMap().entrySet()) {
        Id.NamespacedId data = collapsedEntry.getKey().data;
        Id.Program program = collapsedEntry.getKey().program;

        Set<AccessType> accessTypes = new HashSet<>();
        Set<RunId> runs = new HashSet<>();
        Set<Id.NamespacedId> components = new HashSet<>();

        for (Relation relation : collapsedEntry.getValue()) {
            accessTypes.add(relation.getAccess());
            runs.add(relation.getRun());
            components.addAll(relation.getComponents());
        }
        collapsedRelations.add(toCollapsedRelation(data, program, accessTypes, runs, components));
    }
    return collapsedRelations;
}

From source file:gobblin.util.PublisherUtils.java

/**
 * Given a {@link Multimap} of {@link Extract}s to {@link WorkUnitState}s, filter out any {@link Extract}s where all
 * of the corresponding {@link WorkUnitState}s do not meet the given {@link Predicate}.
 * <ul>/* w w w .  j  a  v  a 2  s  .  c  o  m*/
 *  <li> The filtered {@link Extract}s will be available in {@link SplitExtractsResult#getFiltered()}</li>
 *  <li> The {@link Extract}s satisfying the predicated will be available in {@link SplitExtractsResult#getRetained()}</li>
 * </ul>
 *
 */
public static SplitExtractsResult splitExtractsByPredicate(
        Multimap<Extract, WorkUnitState> extractToWorkUnitStateMap, Predicate<WorkUnitState> predicate) {
    Multimap<Extract, WorkUnitState> retained = ArrayListMultimap.create();
    Multimap<Extract, WorkUnitState> filtered = ArrayListMultimap.create();
    for (Map.Entry<Extract, Collection<WorkUnitState>> entry : extractToWorkUnitStateMap.asMap().entrySet()) {
        if (Iterables.all(entry.getValue(), predicate)) {
            retained.putAll(entry.getKey(), entry.getValue());
        } else {
            filtered.putAll(entry.getKey(), entry.getValue());
        }
    }
    return new SplitExtractsResult(retained, filtered);
}

From source file:org.jclouds.aws.util.AWSUtils.java

public static <R extends HttpRequest> R indexMultimapToFormValuesWithPrefix(R request, String prefix,
        String keySuffix, String valueSuffix, Object input) {
    checkArgument(checkNotNull(input, "input") instanceof Multimap<?, ?>,
            "this binder is only valid for Multimap<?,?>: " + input.getClass());
    Multimap<Object, Object> map = (Multimap<Object, Object>) input;
    Builder<String, String> builder = ImmutableMultimap.builder();
    int i = 1;//from   ww w.  jav a 2s. co  m
    for (Map.Entry<Object, Collection<Object>> entry : map.asMap().entrySet()) {
        builder.put(prefix + "." + i + "." + keySuffix,
                checkNotNull(entry.getKey().toString(), keySuffix.toLowerCase() + "s[" + i + "]"));
        int j = 1;
        for (Object v : entry.getValue()) {
            builder.put(prefix + "." + i + "." + valueSuffix + "." + j, v.toString());
            j++;
        }
        i++;
    }
    ImmutableMultimap<String, String> forms = builder.build();
    return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();
}

From source file:prm4j.spec.finite.FiniteParametricProperty.java

/**
 * Return a multimap {something -> parameterset} for a multimap {something -> baseEvent}.
 * //from w  w  w.jav  a2 s  .c  o m
 * @param baseEventMultimap
 * @return
 */
private static <T> SetMultimap<T, Set<Parameter<?>>> toParameterSetMultimap(
        Multimap<T, Set<BaseEvent>> baseEventMultimap) {
    final SetMultimap<T, Set<Parameter<?>>> result = HashMultimap.create();
    final Map<T, Collection<Set<BaseEvent>>> mapBaseEvent2SetOfSetOfBaseEvents = baseEventMultimap.asMap();
    for (Entry<T, Collection<Set<BaseEvent>>> entry : mapBaseEvent2SetOfSetOfBaseEvents.entrySet()) {
        for (Set<Parameter<?>> parameterSet : toParameterSets(entry.getValue())) {
            result.put(entry.getKey(), parameterSet);
        }
    }
    return result;
}

From source file:com.google.devtools.build.lib.profiler.statistics.SkylarkStatistics.java

/**
 * Add all new durations to previously collected durations for all functions mapped to tasks.
 * @return The sum of the execution times of all {@link Task} values in the map.
 *//*from   ww w . j a  v  a  2s  . c  o  m*/
private static long addDurations(Multimap<String, Task> functionTasks, Map<String, LongArrayList> durationsMap,
        Map<String, LongArrayList> selfDurationsMap) {
    long totalTime = 0;
    for (Entry<String, Collection<Task>> entry : functionTasks.asMap().entrySet()) {
        String function = entry.getKey();
        Collection<Task> tasks = entry.getValue();
        LongArrayList durations;
        LongArrayList selfDurations;
        if (durationsMap.containsKey(function)) {
            durations = durationsMap.get(function);
            selfDurations = selfDurationsMap.get(function);
        } else {
            durations = new LongArrayList(tasks.size());
            selfDurations = new LongArrayList(tasks.size());
            durationsMap.put(function, durations);
            selfDurationsMap.put(function, selfDurations);
        }
        totalTime += addDurations(tasks, durations, selfDurations);
    }
    return totalTime;
}

From source file:org.ambraproject.wombat.config.site.SiteSet.java

/**
 * Build a map representing the one-to-one relationship between journal keys and journal names.
 * <p/>//from w w w  . ja  v a2  s. c  o  m
 * As a side effect, validates that the relationship actually is one-to-one -- that is, that multiple sites have the
 * same journal key if and only if they have the same journal name. It is easier to obey this constraint if the {@code
 * journalKey} and {@code journalName} config values are always set in the {@code journal.yaml} or {@code
 * journal.json} file of the same theme, which should be a parent of all themes belonging to that journal.
 *
 * @param sites the set of all sites being served
 * @return a map between journal keys and journal names
 * @throws IllegalArgumentException if two sites with the same journal key have unequal journal names or if two sites
 *                                  with the same journal name have unequal journal keys
 */
private static ImmutableBiMap<String, String> buildJournalKeysToNames(Set<Site> sites) {
    Multimap<String, Site> keysToSites = groupByJournalKey(sites);
    BiMap<String, String> keysToNames = HashBiMap.create(keysToSites.keySet().size());
    for (Map.Entry<String, Collection<Site>> entry : keysToSites.asMap().entrySet()) {
        String journalKey = entry.getKey();
        Iterator<Site> siteIterator = entry.getValue().iterator();
        String journalName = siteIterator.next().getJournalName();
        while (siteIterator.hasNext()) {
            String nextJournalName = siteIterator.next().getJournalName();
            if (!journalName.equals(nextJournalName)) {
                String message = String.format("Inconsistent journal names with key=%s: %s; %s", journalKey,
                        journalName, nextJournalName);
                throw new IllegalArgumentException(message);
            }
        }

        if (keysToNames.containsValue(journalName)) {
            String message = String.format("Overloaded journal name (%s) for keys: %s; %s", journalName,
                    journalKey, keysToNames.inverse().get(journalName));
            throw new IllegalArgumentException(message);
        }
        keysToNames.put(journalKey, journalName);
    }
    return ImmutableBiMap.copyOf(keysToNames);
}

From source file:org.apache.shindig.common.JsonSerializer.java

/**
 * Appends a Map to the buffer.//from www . ja v a 2  s  . c o  m
 *
 * @throws IOException If {@link Appendable#append(char)} throws an exception.
 */
public static void appendMultimap(Appendable buf, Multimap<String, Object> map) throws IOException {
    appendMap(buf, map.asMap());
}

From source file:com.b2international.snowowl.snomed.datastore.request.DescriptionRequestHelper.java

private static <T> Map<String, SnomedDescription> extractBest(
        Multimap<String, SnomedDescription> descriptionsByConceptId, List<T> orderedValues,
        Function<SnomedDescription, T> predicateFactory) {

    Map<String, SnomedDescription> uniqueMap = Maps.transformValues(descriptionsByConceptId.asMap(),
            new ExtractBestFunction<T>(orderedValues, predicateFactory));
    return ImmutableMap.copyOf(Maps.filterValues(uniqueMap, Predicates.notNull()));
}

From source file:org.ambraproject.wombat.config.site.SiteRequestCondition.java

/**
 * Create a condition, representing all sites, for a single request handler.
 * <p>//from  ww  w  .j a  v  a 2 s .c  om
 * Writes to the {@link RequestMappingContextDictionary} object as a side effect. To avoid redundant writes, this
 * method must be called only once per {@link RequestMapping} object.
 *
 * @param siteResolver                    the global site resolver
 * @param siteSet                         the set of all sites in the system
 * @param controllerMethod                the method annotated with the request handler
 * @param requestMappingContextDictionary the global handler directory, which must be in a writable state
 * @return the new condition object
 */
public static SiteRequestCondition create(SiteResolver siteResolver, SiteSet siteSet, Method controllerMethod,
        RequestMappingContextDictionary requestMappingContextDictionary) {
    RequestMappingContext baseMapping = RequestMappingContext.create(controllerMethod);
    if (baseMapping.isSiteless()) {
        PatternsRequestCondition patternsRequestCondition = new PatternsRequestCondition(
                baseMapping.getPattern());
        requestMappingContextDictionary.registerGlobalMapping(baseMapping);
        return forSiteless(patternsRequestCondition);
    }

    Multimap<RequestMappingContext, Site> patternMap = buildPatternMap(siteSet, baseMapping);

    ImmutableMap.Builder<Site, PatternsRequestCondition> requestConditionMap = ImmutableMap.builder();
    for (Map.Entry<RequestMappingContext, Collection<Site>> entry : patternMap.asMap().entrySet()) {
        RequestMappingContext mapping = entry.getKey();
        Collection<Site> sites = entry.getValue(); // all sites that share the mapping pattern

        PatternsRequestCondition condition = new PatternsRequestCondition(mapping.getPattern());
        for (Site site : sites) {
            requestConditionMap.put(site, condition);
            if (!mapping.getAnnotation().name().isEmpty()) {
                requestMappingContextDictionary.registerSiteMapping(mapping, site);
            }
        }
    }

    return forSiteMap(siteResolver, requestConditionMap.build());
}

From source file:com.google.errorprone.bugpatterns.WildcardImport.java

/** Creates a {@link Fix} that replaces wildcard imports. */
static Fix createFix(ImmutableList<ImportTree> wildcardImports, Multimap<ImportTree, TypeToImport> toFix,
        VisitorState state) {//from w w  w. j av  a 2 s. co  m
    final SuggestedFix.Builder fix = SuggestedFix.builder();
    for (ImportTree importToDelete : wildcardImports) {
        String importSpecification = importToDelete.getQualifiedIdentifier().toString();
        if (importToDelete.isStatic()) {
            fix.removeStaticImport(importSpecification);
        } else {
            fix.removeImport(importSpecification);
        }
    }
    Multimap<Symbol, TypeToImport> importsByOwner = LinkedHashMultimap.create();
    for (TypeToImport toImport : toFix.values()) {
        importsByOwner.put(toImport.owner(), toImport);
    }
    for (Map.Entry<Symbol, Collection<TypeToImport>> entries : importsByOwner.asMap().entrySet()) {
        final Symbol owner = entries.getKey();
        if (entries.getValue().size() > MAX_MEMBER_IMPORTS) {
            qualifiedNameFix(fix, owner, state);
        } else {
            for (TypeToImport toImport : toFix.values()) {
                toImport.addFix(fix);
            }
        }
    }
    return fix.build();
}