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

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

Introduction

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

Prototype

Collection<Map.Entry<K, V>> entries();

Source Link

Document

Returns a view collection of all key-value pairs contained in this multimap, as Map.Entry instances.

Usage

From source file:com.jcwhatever.nucleus.utils.CollectionUtils.java

/**
 * Removes all matching instances of a value from the specified
 * {@link com.google.common.collect.Multimap}.
 *
 * @param multimap  The multimap.//from   www .j  a v a  2s  .  c o  m
 * @param value     The value to remove.
 *
 * @param <K>  The key type.
 * @param <V>  The value type.
 *
 * @return  True if the {@link com.google.common.collect.Multimap} was modified.
 */
public static <K, V> boolean removeValue(Multimap<K, V> multimap, @Nullable Object value) {
    return removeValue(multimap.entries(), value);
}

From source file:eu.tomylobo.routes.util.Ini.java

public static void save(String fileName, Multimap<String, Multimap<String, String>> sections) {
    try {//from  w ww.ja  v  a2s.  com
        final File file = new File(fileName);
        file.getAbsoluteFile().getParentFile().mkdirs();
        BufferedWriter stream = new BufferedWriter(new FileWriter(file));
        for (Entry<String, Multimap<String, String>> entry : sections.entries()) {
            stream.write("[" + entry.getKey() + "]");
            stream.newLine();
            saveSection(stream, entry.getValue());
            stream.newLine();
        }
        stream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:me.lucko.luckperms.api.context.MutableContextSet.java

/**
 * Creates a MutableContextSet from an existing multimap
 *
 * @param multimap the multimap to copy from
 * @return a new MutableContextSet representing the pairs in the multimap
 * @throws NullPointerException if the multimap is null
 *//*w  w w .  j  a  va 2s.c om*/
public static MutableContextSet fromMultimap(Multimap<String, String> multimap) {
    if (multimap == null) {
        throw new NullPointerException("multimap");
    }

    return fromEntries(multimap.entries());
}

From source file:com.torodb.torod.db.postgresql.meta.routines.DeleteDocuments.java

public static int execute(Configuration configuration, CollectionSchema colSchema,
        Multimap<DocStructure, Integer> didsByStructure, boolean justOne) {
    Multimap<DocStructure, Integer> didsByStructureToDelete;
    if (didsByStructure.isEmpty()) {
        return 0;
    }//from  ww w. ja  v  a2s.com

    if (justOne) {
        didsByStructureToDelete = MultimapBuilder.hashKeys(1).arrayListValues(1).build();

        Map.Entry<DocStructure, Integer> aEntry = didsByStructure.entries().iterator().next();

        didsByStructureToDelete.put(aEntry.getKey(), aEntry.getValue());
    } else {
        didsByStructureToDelete = didsByStructure;
    }

    try {
        return execute(configuration, colSchema, didsByStructureToDelete);
    } catch (SQLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:grakn.core.graql.reasoner.pattern.RelationPattern.java

/**
 * Generates different relation patterns variants as a cartesian products of provided id configurations.
 *
 * ( (role label): $x, (role label): $y, ...) {T1(x), T2(y), ...}, {[x/...], [y/...], ...}
 *
 * NB: only roleplayer ids are involved in the Cartesian Product
 *
 * Example:/*from www  . ja v  a2  s .  co m*/
 * [someRole, someType, {V123, V456, V789} ]
 * [anotherRole, x, {V123}]
 * [yetAnotherRole, x, {V456}]
 *
 * Will generate the following relations:
 *
 * {Type cartesian product},
 * {Role Player Id cartesian product}
 * {Rel id variants}
 *
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), someType($genVarA)
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), [$genVarA/V123], [$genVarB/V123], [$genVarC/V456]
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), [$genVarA/V456], [$genVarB/V123], [$genVarC/V456]
 * (someRole: $genVarA, anotherRole: $genVarB, yetAnotherRole: $genVarC), [$genVarA/V789], [$genVarB/V123], [$genVarC/V456]
 *
 * @param spec roleplayer configuration in the form {role} -> {type label, {ids...}}
 * @param relationIds list of id mappings for relation variable
 * @return list of generated patterns as strings
 */
private static List<Pattern> generateRelationPatterns(
        Multimap<RelationProperty.RolePlayer, Pair<Label, List<ConceptId>>> spec, List<ConceptId> relationIds) {
    Statement relationVar = !relationIds.isEmpty() ? new Statement(new Variable().asReturnedVar())
            : Graql.var();
    Statement[] basePattern = { relationVar };
    List<List<Pattern>> rpTypePatterns = new ArrayList<>();
    List<List<Pattern>> rpIdPatterns = new ArrayList<>();
    spec.entries().forEach(entry -> {
        RelationProperty.RolePlayer rp = entry.getKey();
        Statement role = rp.getRole().orElse(null);

        Statement rolePlayer = new Statement(entry.getKey().getPlayer().var().asReturnedVar());

        Label type = entry.getValue().getKey();
        List<ConceptId> ids = entry.getValue().getValue();
        basePattern[0] = basePattern[0].rel(role, rolePlayer);

        //rps.put(role, rolePlayer);

        List<Pattern> rpPattern = Lists.newArrayList(rolePlayer);
        List<Pattern> typePattern = Lists.newArrayList(rolePlayer);
        if (type != null)
            typePattern.add(rolePlayer.isa(type.getValue()));

        ids.forEach(id -> {
            Statement idPattern = rolePlayer.id(id.getValue());
            rpPattern.add(idPattern);
        });

        rpIdPatterns.add(rpPattern);
        rpTypePatterns.add(typePattern);
    });
    List<Pattern> relIdPatterns = new ArrayList<>();
    relationIds
            .forEach(relId -> relIdPatterns.add(Graql.and(basePattern[0], relationVar.id(relId.getValue()))));

    List<Pattern> patterns = new ArrayList<>();

    Stream.concat(Lists.cartesianProduct(rpTypePatterns).stream(),
            Lists.cartesianProduct(rpIdPatterns).stream())
            //filter trivial patterns
            .map(l -> l.stream()
                    .filter(p -> (p instanceof Conjunction)
                            || ((Statement) p).properties().stream().findFirst().isPresent())
                    .collect(Collectors.toList()))
            .forEach(product -> {
                Pattern[] pattern = { basePattern[0] };
                product.forEach(p -> pattern[0] = Graql.and(pattern[0], p));
                if (!patterns.contains(pattern[0]))
                    patterns.add(pattern[0]);
            });
    return Stream.concat(patterns.stream(), relIdPatterns.stream()).collect(Collectors.toList());
}

From source file:ai.grakn.graql.internal.query.QueryOperationExecutor.java

/**
 * <a href=https://en.wikipedia.org/wiki/Composition_of_relations>Compose</a> two {@link Multimap}s together,
 * treating them like many-to-many relations.
 *//*from  ww w .  j  ava 2  s  . c o m*/
private static <K, T, V> Multimap<K, V> composeMultimaps(Multimap<K, T> map1, Multimap<T, V> map2) {
    Multimap<K, V> composed = HashMultimap.create();

    for (Map.Entry<K, T> entry1 : map1.entries()) {
        K key = entry1.getKey();
        T intermediateValue = entry1.getValue();

        for (V value : map2.get(intermediateValue)) {
            composed.put(key, value);
        }
    }

    return composed;
}

From source file:org.opendaylight.protocol.bgp.linkstate.impl.attribute.NodeAttributesParser.java

/**
 * Parse Node Attributes.//from   w  ww  .j  a va  2 s .  c  o m
 *
 * @param attributes key is the tlv type and value is the value of the tlv
 * @param protocolId to differentiate parsing methods
 * @return {@link LinkStateAttribute}
 */
static LinkStateAttribute parseNodeAttributes(final Multimap<Integer, ByteBuf> attributes,
        final ProtocolId protocolId) {
    final List<TopologyIdentifier> topologyMembership = new ArrayList<>();
    final List<IsisAreaIdentifier> areaMembership = new ArrayList<>();
    final NodeAttributesBuilder builder = new NodeAttributesBuilder();
    for (final Entry<Integer, ByteBuf> entry : attributes.entries()) {
        final int key = entry.getKey();
        final ByteBuf value = entry.getValue();
        LOG.trace("Node attribute TLV {}", key);
        switch (key) {
        case TlvUtil.MULTI_TOPOLOGY_ID:
            parseTopologyId(topologyMembership, value);
            break;
        case NODE_FLAG_BITS:
            parseNodeFlags(value, builder);
            break;
        case NODE_OPAQUE:
            if (LOG.isDebugEnabled()) {
                LOG.debug("Ignoring opaque value: {}.", ByteBufUtil.hexDump(value));
            }
            break;
        case DYNAMIC_HOSTNAME:
            builder.setDynamicHostname(new String(ByteArray.readAllBytes(value), StandardCharsets.US_ASCII));
            LOG.debug("Parsed Node Name {}", builder.getDynamicHostname());
            break;
        case ISIS_AREA_IDENTIFIER:
            final IsisAreaIdentifier ai = new IsisAreaIdentifier(ByteArray.readAllBytes(value));
            areaMembership.add(ai);
            LOG.debug("Parsed AreaIdentifier {}", ai);
            break;
        case TlvUtil.LOCAL_IPV4_ROUTER_ID:
            final Ipv4RouterIdentifier ip4 = new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value));
            builder.setIpv4RouterId(ip4);
            LOG.debug("Parsed IPv4 Router Identifier {}", ip4);
            break;
        case TlvUtil.LOCAL_IPV6_ROUTER_ID:
            final Ipv6RouterIdentifier ip6 = new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value));
            builder.setIpv6RouterId(ip6);
            LOG.debug("Parsed IPv6 Router Identifier {}", ip6);
            break;
        case SR_CAPABILITIES:
            final SrCapabilities caps = SrNodeAttributesParser.parseSrCapabilities(value, protocolId);
            builder.setSrCapabilities(caps);
            LOG.debug("Parsed SR Capabilities {}", caps);
            break;
        case SR_ALGORITHMS:
            final SrAlgorithm algs = SrNodeAttributesParser.parseSrAlgorithms(value);
            builder.setSrAlgorithm(algs);
            LOG.debug("Parsed SR Algorithms {}", algs);
            break;
        default:
            LOG.warn("TLV {} is not a valid node attribute, ignoring it", key);
        }
    }
    LOG.trace("Finished parsing Node Attributes.");
    builder.setTopologyIdentifier(topologyMembership);
    builder.setIsisAreaId(areaMembership);
    return new NodeAttributesCaseBuilder().setNodeAttributes(builder.build()).build();
}

From source file:org.opendaylight.protocol.bgp.linkstate.attribute.NodeAttributesParser.java

/**
 * Parse Node Attributes./* ww w .  jav a  2 s  .  c o m*/
 *
 * @param attributes key is the tlv type and value is the value of the tlv
 * @param protocolId to differentiate parsing methods
 * @return {@link LinkStateAttribute}
 */
static LinkStateAttribute parseNodeAttributes(final Multimap<Integer, ByteBuf> attributes,
        final ProtocolId protocolId) {
    final List<TopologyIdentifier> topologyMembership = new ArrayList<>();
    final List<IsisAreaIdentifier> areaMembership = new ArrayList<>();
    final NodeAttributesBuilder builder = new NodeAttributesBuilder();
    for (final Entry<Integer, ByteBuf> entry : attributes.entries()) {
        final int key = entry.getKey();
        final ByteBuf value = entry.getValue();
        LOG.trace("Node attribute TLV {}", key);
        switch (key) {
        case TlvUtil.MULTI_TOPOLOGY_ID:
            parseTopologyId(topologyMembership, value);
            break;
        case NODE_FLAG_BITS:
            final BitArray flags = BitArray.valueOf(value, FLAGS_SIZE);
            builder.setNodeFlags(new NodeFlagBits(flags.get(OVERLOAD_BIT), flags.get(ATTACHED_BIT),
                    flags.get(EXTERNAL_BIT), flags.get(ABBR_BIT), flags.get(ROUTER_BIT), flags.get(V6_BIT)));
            LOG.debug("Parsed Overload bit: {}, attached bit: {}, external bit: {}, area border router: {}.",
                    flags.get(OVERLOAD_BIT), flags.get(ATTACHED_BIT), flags.get(EXTERNAL_BIT),
                    flags.get(ABBR_BIT));
            break;
        case NODE_OPAQUE:
            if (LOG.isDebugEnabled()) {
                LOG.debug("Ignoring opaque value: {}.", ByteBufUtil.hexDump(value));
            }
            break;
        case DYNAMIC_HOSTNAME:
            builder.setDynamicHostname(new String(ByteArray.readAllBytes(value), Charsets.US_ASCII));
            LOG.debug("Parsed Node Name {}", builder.getDynamicHostname());
            break;
        case ISIS_AREA_IDENTIFIER:
            final IsisAreaIdentifier ai = new IsisAreaIdentifier(ByteArray.readAllBytes(value));
            areaMembership.add(ai);
            LOG.debug("Parsed AreaIdentifier {}", ai);
            break;
        case TlvUtil.LOCAL_IPV4_ROUTER_ID:
            final Ipv4RouterIdentifier ip4 = new Ipv4RouterIdentifier(Ipv4Util.addressForByteBuf(value));
            builder.setIpv4RouterId(ip4);
            LOG.debug("Parsed IPv4 Router Identifier {}", ip4);
            break;
        case TlvUtil.LOCAL_IPV6_ROUTER_ID:
            final Ipv6RouterIdentifier ip6 = new Ipv6RouterIdentifier(Ipv6Util.addressForByteBuf(value));
            builder.setIpv6RouterId(ip6);
            LOG.debug("Parsed IPv6 Router Identifier {}", ip6);
            break;
        case SR_CAPABILITIES:
            final SrCapabilities caps = SrNodeAttributesParser.parseSrCapabilities(value, protocolId);
            builder.setSrCapabilities(caps);
            LOG.debug("Parsed SR Capabilities {}", caps);
            break;
        case SR_ALGORITHMS:
            final SrAlgorithm algs = SrNodeAttributesParser.parseSrAlgorithms(value);
            builder.setSrAlgorithm(algs);
            LOG.debug("Parsed SR Algorithms {}", algs);
            break;
        default:
            LOG.warn("TLV {} is not a valid node attribute, ignoring it", key);
        }
    }
    LOG.trace("Finished parsing Node Attributes.");
    builder.setTopologyIdentifier(topologyMembership);
    builder.setIsisAreaId(areaMembership);
    return new NodeAttributesCaseBuilder().setNodeAttributes(builder.build()).build();
}

From source file:grakn.core.graql.executor.WriteExecutor.java

/**
 * <a href=https://en.wikipedia.org/wiki/Composition_of_relations>Compose</a> two Multimaps together,
 * treating them like many-to-many relations.
 *//*from w  w w .ja va2 s.  c o m*/
private static Multimap<Writer, Writer> writerDependencies(Multimap<Writer, Variable> writerToVar,
        Multimap<Variable, Writer> varToWriter) {
    Multimap<Writer, Writer> dependency = HashMultimap.create();

    for (Map.Entry<Writer, Variable> entry : writerToVar.entries()) {
        Writer dependant = entry.getKey();
        Variable intermediateVar = entry.getValue();

        for (Writer depended : varToWriter.get(intermediateVar)) {
            dependency.put(dependant, depended);
        }
    }

    return dependency;
}

From source file:org.sonar.api.utils.KeyValueFormat.java

/**
 * Limitation: there's currently no methods to parse into Multimap.
 *
 * @since 2.7//from  w  ww .java2 s.  com
 */
public static <K, V> String format(Multimap<K, V> map, Converter<K> keyConverter, Converter<V> valueConverter) {
    return formatEntries(map.entries(), keyConverter, valueConverter);
}