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:prm4jeval.dataanalysis.AnalysisResultsTableWriter.java

private static Map<String, Double> toOverheadSumMap(Multimap<String, Double> experiment) {
    final Map<String, Double> result = new HashMap<String, Double>();
    for (Entry<String, Collection<Double>> entry : experiment.asMap().entrySet()) {
        result.put(entry.getKey(), sumCollection(entry.getValue()));
    }/*  w w  w  .  ja  va  2  s.c o m*/
    return result;
}

From source file:com.sam.moca.web.WebResults.java

private static void writeObject(Object object, JsonGenerator jgen) throws JsonGenerationException, IOException {
    if (object instanceof Multimap<?, ?>) {
        Multimap<?, ?> multimap = (Multimap<?, ?>) object;

        for (Entry<?, ?> entry : multimap.asMap().entrySet()) {
            jgen.writeStartObject();/*from w  w w  .j av a 2s  . c  o  m*/
            jgen.writeObjectField("name", entry.getKey());
            jgen.writeObjectField("value", entry.getValue());
            jgen.writeEndObject();
        }
    } else if (object instanceof Map<?, ?>) {
        Map<?, ?> map = (Map<?, ?>) object;

        for (Entry<?, ?> entry : map.entrySet()) {
            jgen.writeStartObject();
            jgen.writeObjectField("name", entry.getKey());
            jgen.writeObjectField("value", entry.getValue());
            jgen.writeEndObject();
        }
    } else if (object instanceof MocaResults) {
        MocaResults res = (MocaResults) object;
        RowIterator iter = res.getRows();
        while (iter.next()) {
            jgen.writeStartObject();
            for (int j = 0; j < res.getColumnCount(); ++j) {
                jgen.writeObjectField(res.getColumnName(j), iter.getValue(j));
            }
            jgen.writeEndObject();
        }
    } else {
        jgen.writeObject(object);
    }
}

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}.
 *//*  w  ww . jav  a  2s. c  o  m*/
public static Multimap<Extract, WorkUnitState> getExtractsForPredicate(
        Multimap<Extract, WorkUnitState> extractToWorkUnitStateMap, Predicate<WorkUnitState> predicate) {
    Multimap<Extract, WorkUnitState> successfulExtracts = ArrayListMultimap.create();
    for (Map.Entry<Extract, Collection<WorkUnitState>> entry : extractToWorkUnitStateMap.asMap().entrySet()) {
        if (Iterables.all(entry.getValue(), predicate)) {
            successfulExtracts.putAll(entry.getKey(), entry.getValue());
        }
    }
    return successfulExtracts;
}

From source file:org.ketsu.jdbc.CustomTypeArray.java

public static <K, V> java.sql.Array toArray(String typeName, Multimap<K, V> m) {
    if (m == null) {
        return null;
    }/*from  ww w  .  j a  v a2s.com*/

    Collection<CustomType> b = new ArrayList<CustomType>();

    for (Map.Entry<K, Collection<V>> entry : m.asMap().entrySet()) {
        CustomType t = new CustomType();

        t.set(1, entry.getKey());
        t.set(2, entry.getValue().toArray());

        b.add(t);
    }

    return new CustomTypeArray(typeName, b);
}

From source file:org.apache.aurora.scheduler.base.Conversions.java

/**
 * Converts protobuf attributes into thrift-generated attributes.
 *
 * @param offer Resource offer./*from www  .j  av  a  2 s . c om*/
 * @return Equivalent thrift host attributes.
 */
public static IHostAttributes getAttributes(Offer offer) {
    // Group by attribute name.
    Multimap<String, Protos.Attribute> valuesByName = Multimaps.index(offer.getAttributesList(),
            ATTRIBUTE_NAME);

    return IHostAttributes.build(new HostAttributes(offer.getHostname(),
            FluentIterable.from(valuesByName.asMap().entrySet()).transform(ATTRIBUTE_CONVERTER).toSet())
                    .setSlaveId(offer.getAgentId().getValue()));
}

From source file:eu.itesla_project.commons.tools.Main.java

private static void printUsage() {
    StringBuilder usage = new StringBuilder();
    usage.append("usage: " + TOOL_NAME + " COMMAND [ARGS]\n\nAvailable commands are:\n\n");

    List<Tool> allTools = Lists.newArrayList(ServiceLoader.load(Tool.class)).stream()
            .filter(t -> !t.getCommand().isHidden()).collect(Collectors.toList());

    // group commands by theme
    Multimap<String, Tool> toolsByTheme = Multimaps.index(allTools, new Function<Tool, String>() {
        @Override//from w  w  w  . ja v  a 2  s . c  o  m
        public String apply(Tool tool) {
            return tool.getCommand().getTheme();
        }
    });

    for (Map.Entry<String, Collection<Tool>> entry : toolsByTheme.asMap().entrySet()) {
        String theme = entry.getKey();
        List<Tool> tools = new ArrayList<>(entry.getValue());
        Collections.sort(tools, new Comparator<Tool>() {
            @Override
            public int compare(Tool t1, Tool t2) {
                return t1.getCommand().getName().compareTo(t2.getCommand().getName());
            }
        });
        usage.append(theme != null ? theme : "Others").append(":\n");
        for (Tool tool : tools) {
            usage.append(String.format("   %-40s %s", tool.getCommand().getName(),
                    tool.getCommand().getDescription())).append("\n");
        }
        usage.append("\n");
    }

    System.err.print(usage);
    System.exit(1);
}

From source file:com.twitter.aurora.scheduler.base.Conversions.java

/**
 * Converts protobuf attributes into thrift-generated attributes.
 *
 * @param offer Resource offer.//  w  w  w. j  a v  a2  s .c om
 * @return Equivalent thrift host attributes.
 */
public static HostAttributes getAttributes(Offer offer) {
    // Group by attribute name.
    Multimap<String, Protos.Attribute> valuesByName = Multimaps.index(offer.getAttributesList(),
            ATTRIBUTE_NAME);

    // TODO(William Farner): Include slave id.
    return new HostAttributes(offer.getHostname(),
            FluentIterable.from(valuesByName.asMap().entrySet()).transform(ATTRIBUTE_CONVERTER).toSet())
                    .setSlaveId(offer.getSlaveId().getValue());
}

From source file:com.google.devtools.build.lib.analysis.constraints.TopLevelConstraintSemantics.java

/**
 * Prepares a user-friendly error message for a list of targets missing support for required
 * environments./*from w  ww.ja  v a 2s .co  m*/
 */
private static String getBadTargetsUserMessage(Multimap<ConfiguredTarget, Label> badTargets) {
    StringBuilder msg = new StringBuilder();
    msg.append("This is a restricted-environment build.");
    for (Map.Entry<ConfiguredTarget, Collection<Label>> entry : badTargets.asMap().entrySet()) {
        msg.append(
                String.format("\n - %s does not support required environment%s %s.", entry.getKey().getLabel(),
                        entry.getValue().size() == 1 ? "" : "s", Joiner.on(", ").join(entry.getValue())));
    }
    return msg.toString();
}

From source file:com.twitter.common.collections.Multimaps.java

/**
 * Prunes a multimap based on a predicate, returning the pruned values.  The input map will be
 * modified./*from w ww .  j  a  v a  2  s . c o  m*/
 *
 * @param map The multimap to prune.
 * @param filterRule The pruning rule.  When the predicate returns {@code false} for an entry, it
 *    will be pruned, otherwise it will be retained.
 * @param <K> The key type in the multimap.
 * @param <V> The value type in the multimap.
 * @return A new multimap, containing the pruned keys/values.
 */
public static <K, V> Multimap<K, V> prune(Multimap<K, V> map, Predicate<? super Collection<V>> filterRule) {
    Preconditions.checkNotNull(map);
    Preconditions.checkNotNull(filterRule);
    Multimap<K, V> pruned = ArrayListMultimap.create();
    Iterator<Map.Entry<K, Collection<V>>> asMapItr = map.asMap().entrySet().iterator();
    while (asMapItr.hasNext()) {
        Map.Entry<K, Collection<V>> asMapEntry = asMapItr.next();
        if (!filterRule.apply(asMapEntry.getValue())) {
            pruned.putAll(asMapEntry.getKey(), asMapEntry.getValue());
            asMapItr.remove();
        }
    }

    return pruned;
}

From source file:com.redprairie.moca.components.mocatest.ClusterTestComponent.java

/**
 * Gets a result set of node|roles which is each
 * node URL to a comma separated list of roles
 * @return//from w  ww  .j a  v  a 2s.  c  om
 */
public static MocaResults getNodesToRoles() {
    SimpleResults res = new SimpleResults();
    res.addColumn("node", MocaType.STRING);
    res.addColumn("roles", MocaType.STRING);

    ClusterRoleManager manager = ServerUtils.globalAttribute(ClusterRoleManager.class);
    MocaClusterAdministration admin = (MocaClusterAdministration) ServerUtils.globalContext()
            .getAttribute(MocaClusterAdministration.class.getName());
    if (manager != null && admin != null) {
        Multimap<Node, RoleDefinition> multiMap = manager.getClusterRoles();
        Map<Node, InstanceUrl> urls = admin.getKnownNodes();
        _logger.info("Cluster URLs: " + urls.entrySet());
        _logger.info("Node to Roles: " + multiMap.asMap().entrySet());

        Multimap<InstanceUrl, RoleDefinition> urlRoleMap = HashMultimap.create();

        for (Entry<Node, Collection<RoleDefinition>> entry : multiMap.asMap().entrySet()) {
            InstanceUrl url = urls.get(entry.getKey());
            // TODO: trying to handle that cluster URLs is wrong and doesn't contain the entry
            if (url == null) {
                url = new InstanceUrl(false, entry.getKey().toString(), 0);
            }
            urlRoleMap.putAll(url, entry.getValue());
        }

        for (Entry<Node, InstanceUrl> url : urls.entrySet()) {
            if (!urlRoleMap.containsKey(url.getValue())) {
                urlRoleMap.put(url.getValue(), EMPTY_ROLE);
            }
        }

        // Sort by the node url
        Map<InstanceUrl, Collection<RoleDefinition>> sortedMap = new TreeMap<InstanceUrl, Collection<RoleDefinition>>(
                new Comparator<InstanceUrl>() {

                    @Override
                    public int compare(InstanceUrl o1, InstanceUrl o2) {
                        return o1.toString().compareTo(o2.toString());
                    }
                });

        sortedMap.putAll(urlRoleMap.asMap());
        for (Map.Entry<InstanceUrl, Collection<RoleDefinition>> entry : sortedMap.entrySet()) {
            res.addRow();
            res.setStringValue("node", entry.getKey().toString());
            res.setStringValue("roles", Joiner.on(',').join(entry.getValue()));
        }
    } else {
        _logger.info("Cluster manager and/or admin not set");
    }

    return res;
}