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:edu.buaa.satla.analysis.core.predicate.PredicatePrecision.java

private static <K1, K2, V> ListMultimap<K2, V> transformAndMergeKeys(Multimap<K1, V> input,
        Function<? super K1, K2> transformFunction) {

    ListMultimap<K2, V> result = ArrayListMultimap.create();
    for (Map.Entry<K1, Collection<V>> entry : input.asMap().entrySet()) {
        result.putAll(transformFunction.apply(entry.getKey()), entry.getValue());
    }/*from w ww .  j a va2s . co  m*/
    return result;
}

From source file:org.lanternpowered.server.world.chunk.LanternLoadingTicketIO.java

static void save(Path worldFolder, Set<LanternLoadingTicket> tickets) throws IOException {
    final Path file = worldFolder.resolve(TICKETS_FILE);
    if (!Files.exists(file)) {
        Files.createFile(file);// w w w.  jav a2  s.  c  om
    }

    final Multimap<String, LanternLoadingTicket> sortedByPlugin = HashMultimap.create();
    for (LanternLoadingTicket ticket : tickets) {
        sortedByPlugin.put(ticket.getPlugin(), ticket);
    }

    final List<DataView> ticketHolders = new ArrayList<>();
    for (Entry<String, Collection<LanternLoadingTicket>> entry : sortedByPlugin.asMap().entrySet()) {
        final Collection<LanternLoadingTicket> tickets0 = entry.getValue();

        final List<DataView> ticketEntries = new ArrayList<>();
        for (LanternLoadingTicket ticket0 : tickets0) {
            final DataContainer ticketData = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
            ticketData.set(TICKET_TYPE, ticket0 instanceof EntityLoadingTicket ? TYPE_ENTITY : TYPE_NORMAL);
            final int numChunks = ticket0.getNumChunks();
            // Store the list depth for backwards compatible or something,
            // the current forge version doesn't use it either
            ticketData.set(CHUNK_LIST_DEPTH, (byte) Math.min(numChunks, 127));
            // Storing the chunks number, this number is added by us
            ticketData.set(CHUNK_NUMBER, numChunks);
            if (ticket0 instanceof PlayerLoadingTicket) {
                final PlayerLoadingTicket ticket1 = (PlayerLoadingTicket) ticket0;
                // This is a bit strange, since it already added,
                // but if forge uses it...
                ticketData.set(MOD_ID, entry.getKey());
                ticketData.set(PLAYER_UUID, ticket1.getPlayerUniqueId().toString());
            }
            if (ticket0.extraData != null) {
                ticketData.set(MOD_DATA, ticket0.extraData);
            }
            if (ticket0 instanceof EntityChunkLoadingTicket) {
                final EntityChunkLoadingTicket ticket1 = (EntityChunkLoadingTicket) ticket0;
                ticket1.getOrCreateEntityReference().ifPresent(ref -> {
                    final Vector2i position = ref.getChunkCoords();
                    final UUID uniqueId = ref.getUniqueId();
                    ticketData.set(CHUNK_X, position.getX());
                    ticketData.set(CHUNK_Z, position.getY());
                    ticketData.set(ENTITY_UUID_MOST, uniqueId.getMostSignificantBits());
                    ticketData.set(ENTITY_UUID_LEAST, uniqueId.getLeastSignificantBits());
                });
            }
            ticketEntries.add(ticketData);
        }

        ticketHolders.add(DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED)
                .set(HOLDER_NAME, entry.getKey()).set(TICKETS, ticketEntries));
    }

    final DataContainer dataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED)
            .set(HOLDER_LIST, ticketHolders);
    NbtStreamUtils.write(dataContainer, Files.newOutputStream(file), true);
}

From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

private static Set<ConfigGroup> instancesToConfigGroups(Map<Integer, ITaskConfig> tasks) {
    Multimap<ITaskConfig, Integer> instancesByDetails = Multimaps.invertFrom(Multimaps.forMap(tasks),
            HashMultimap.create());/*from  w  w w.  jav a  2s .  c o  m*/
    return ImmutableSet.copyOf(Iterables.transform(instancesByDetails.asMap().entrySet(), TO_GROUP));
}

From source file:org.apache.beam.runners.core.construction.ExecutableStageTranslation.java

/**
 * Creates a human-readable name for a set of stage names that occur in a single stage.
 *
 * <p>This name reflects the nested structure of the stages, as inferred by slashes in the stage
 * names. Sibling stages will be listed as {A, B}, nested stages as A/B, and according to the
 * value of truncateSiblingComposites the nesting stops at the first level that siblings are
 * encountered.//from  ww w. j a  v  a  2  s. c  o  m
 *
 * <p>This is best understood via examples, of which there are several in the tests for this
 * class.
 *
 * @param names a list of full stage names in this fused operation
 * @param truncateSiblingComposites whether to recursively descent into composite operations that
 *     have simblings, or stop the recursion at that level.
 * @return a single string representation of all the stages in this fused operation
 */
public static String generateNameFromTransformNames(Collection<String> names,
        boolean truncateSiblingComposites) {
    Multimap<String, String> groupByOuter = LinkedHashMultimap.create();
    for (String name : names) {
        int index = name.indexOf('/');
        if (index == -1) {
            groupByOuter.put(name, "");
        } else {
            groupByOuter.put(name.substring(0, index), name.substring(index + 1));
        }
    }
    if (groupByOuter.keySet().size() == 1) {
        Map.Entry<String, Collection<String>> outer = Iterables.getOnlyElement(groupByOuter.asMap().entrySet());
        if (outer.getValue().size() == 1 && outer.getValue().contains("")) {
            // Names consisted of a single name without any slashes.
            return outer.getKey();
        } else {
            // Everything is in the same outer stage, enumerate at one level down.
            return String.format("%s/%s", outer.getKey(),
                    generateNameFromTransformNames(outer.getValue(), truncateSiblingComposites));
        }
    } else {
        Collection<String> parts;
        if (truncateSiblingComposites) {
            // Enumerate the outer stages without their composite structure, if any.
            parts = groupByOuter.keySet();
        } else {
            // Enumerate the outer stages with their composite structure, if any.
            parts = groupByOuter.asMap().entrySet().stream()
                    .map(outer -> String
                            .format("%s/%s", outer.getKey(),
                                    generateNameFromTransformNames(outer.getValue(), truncateSiblingComposites))
                            .replaceAll("/$", ""))
                    .collect(Collectors.toList());
        }
        return String.format("{%s}", Joiner.on(", ").join(parts));
    }
}

From source file:jflowmap.views.flowmap.VisualNodeCluster.java

public static List<List<VisualNode>> combineClusters(List<List<VisualNode>> clusters1,
        List<List<VisualNode>> clusters2) {
    Map<VisualNode, Integer> map1 = createNodeToClusterIndexMap(clusters1);
    Map<VisualNode, Integer> map2 = createNodeToClusterIndexMap(clusters2);

    Multimap<Pair<Integer, Integer>, VisualNode> newClusters = LinkedHashMultimap.create();
    for (List<VisualNode> cluster : clusters1) {
        for (VisualNode node : cluster) {
            newClusters.put(Pair.of(map1.get(node), map2.get(node)), node);
        }//from w w  w  .ja v  a2  s .c  o m
    }

    List<List<VisualNode>> newClustersList = Lists.newArrayList();
    for (Pair<Integer, Integer> key : newClusters.asMap().keySet()) {
        newClustersList.add(ImmutableList.copyOf(newClusters.get(key)));
    }

    return newClustersList;
}

From source file:cruise.umple.umpr.core.consistent.Consistents.java

/**
 * Builds an {@link ImportRepositorySet} from the runtime data produced by the {@link ConsoleMain} using 
 * {@link ConsistentsBuilder}.  //w w  w.j  a va 2s .c o  m
 * 
 * @param outputFolder The location the repository lives. 
 * @param allData {@link List} of {@link ImportRuntimeData} to map into new the consistent data structures. 
 * @return Non-{@code null} instance
 */
public static ImportRepositorySet buildImportRepositorySet(final Path outputFolder, final Path srcFolder,
        final Iterable<? extends ImportFSM> allData) {

    final Multimap<Repository, ? extends ImportFSM> dataByRepo = Multimaps.index(allData,
            ImportFSM::getRepository);

    final ConsistentsBuilder cbld = CONSISTENTS_FACTORY.create(outputFolder, srcFolder);
    dataByRepo.asMap().entrySet().forEach(entry -> {
        final Repository key = entry.getKey();
        final ConsistentRepositoryBuilder repoBld = cbld.withRepository(key);

        entry.getValue().forEach(data -> {
            final Path outpath = data.getOutputPath().getFileName();
            if (data.isSuccessful()) {
                repoBld.addSuccessFile(outpath.toString(), data.getImportType(), data.getAttribLoc());
            } else {
                repoBld.addFailedFile(outpath.toString(), data.getImportType(), data.getAttribLoc(),
                        data.getState(), data.getFailure().get());
            }
        });

        repoBld.withCalculatedSuccessRate();
    });

    return cbld.getRepositorySet();
}

From source file:com.google.devtools.build.lib.rules.android.NativeLibs.java

public static NativeLibs fromLinkedNativeDeps(RuleContext ruleContext, String nativeDepsFileName,
        Multimap<String, TransitiveInfoCollection> depsByArchitecture,
        Map<String, CcToolchainProvider> toolchainMap, Map<String, BuildConfiguration> configurationMap)
        throws InterruptedException {
    Map<String, Iterable<Artifact>> result = new LinkedHashMap<>();
    String nativeDepsLibraryBasename = null;
    for (Map.Entry<String, Collection<TransitiveInfoCollection>> entry : depsByArchitecture.asMap()
            .entrySet()) {/*from www  .ja va 2  s .  c o m*/
        CcLinkParams linkParams = AndroidCommon
                .getCcLinkParamsStore(entry.getValue(),
                        ImmutableList.of("-Wl,-soname=lib" + ruleContext.getLabel().getName()))
                .get(/* linkingStatically */ true, /* linkShared */ true);

        Artifact nativeDepsLibrary = NativeDepsHelper.linkAndroidNativeDepsIfPresent(ruleContext, linkParams,
                configurationMap.get(entry.getKey()), toolchainMap.get(entry.getKey()));

        ImmutableList.Builder<Artifact> librariesBuilder = ImmutableList.builder();
        if (nativeDepsLibrary != null) {
            librariesBuilder.add(nativeDepsLibrary);
            nativeDepsLibraryBasename = nativeDepsLibrary.getExecPath().getBaseName();
        }
        librariesBuilder
                .addAll(filterUniqueSharedLibraries(ruleContext, nativeDepsLibrary, linkParams.getLibraries()));
        ImmutableList<Artifact> libraries = librariesBuilder.build();

        if (!libraries.isEmpty()) {
            result.put(entry.getKey(), libraries);
        }
    }
    if (result.isEmpty()) {
        return NativeLibs.EMPTY;
    } else if (nativeDepsLibraryBasename == null) {
        return new NativeLibs(ImmutableMap.copyOf(result), null);
    } else {
        // The native deps name file must be the only file in its directory because ApkBuilder does
        // not have an option to add a particular file to the .apk, only one to add every file in a
        // particular directory.
        Artifact nativeDepsName = ruleContext.getUniqueDirectoryArtifact("nativedeps_filename",
                nativeDepsFileName, ruleContext.getBinOrGenfilesDirectory());
        ruleContext.registerAction(
                FileWriteAction.create(ruleContext, nativeDepsName, nativeDepsLibraryBasename, false));

        return new NativeLibs(ImmutableMap.copyOf(result), nativeDepsName);
    }
}

From source file:org.apache.abdera2.common.templates.Operation.java

private static String toString(Object val, Context context, boolean reserved, boolean explode,
        String explodeDelim, String explodePfx, int len) {
    if (val == null)
        return null;
    String exp = explode && explodeDelim != null ? explodeDelim : ",";
    if (val.getClass().isArray()) {
        if (val instanceof byte[]) {
            return UrlEncoding.encode((byte[]) val);
        } else if (val instanceof char[]) {
            String chars = (String) trim(new String((char[]) val), len);
            return !reserved
                    ? UrlEncoding.encode(normalize(chars),
                            context.isIri() ? CharUtils.Profile.IUNRESERVED : CharUtils.Profile.UNRESERVED)
                    : UrlEncoding.encode(normalize(chars),
                            context.isIri() ? CharUtils.Profile.RESERVEDANDIUNRESERVED
                                    : CharUtils.Profile.RESERVEDANDUNRESERVED);
        } else if (val instanceof short[]) {
            StringBuilder buf = new StringBuilder();
            for (short obj : (short[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof int[]) {
            StringBuilder buf = new StringBuilder();
            for (int obj : (int[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof long[]) {
            StringBuilder buf = new StringBuilder();
            for (long obj : (long[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof double[]) {
            StringBuilder buf = new StringBuilder();
            for (double obj : (double[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof float[]) {
            StringBuilder buf = new StringBuilder();
            for (float obj : (float[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else if (val instanceof boolean[]) {
            StringBuilder buf = new StringBuilder();
            for (boolean obj : (boolean[]) val)
                appendPrim(obj, len, buf, explode, exp, explodePfx);
            return buf.toString();
        } else {//from  ww  w . j  a v  a 2  s . co  m
            StringBuilder buf = new StringBuilder();
            for (Object obj : (Object[]) val) {
                appendif(buf.length() > 0, buf, exp);
                appendif(explode && explodePfx != null, buf, explodePfx);
                buf.append(toString(obj, context, reserved, false, null, null, len));
            }
            return buf.toString();
        }
    } else if (val instanceof InputStream) {
        try {
            if (len > -1) {
                byte[] buf = new byte[len];
                int r = ((InputStream) val).read(buf);
                return r > 0 ? UrlEncoding.encode(buf, 0, r) : "";
            } else
                return UrlEncoding.encode((InputStream) val);
        } catch (IOException e) {
            throw ExceptionHelper.propogate(e);
        }
    } else if (val instanceof Readable) {
        try {
            if (len > -1) {
                CharBuffer buf = CharBuffer.allocate(len);
                int r = ((Readable) val).read(buf);
                buf.limit(r);
                buf.position(0);
                val = buf;
            }
            return !reserved
                    ? UrlEncoding.encode((Readable) val, "UTF-8",
                            context.isIri() ? CharUtils.Profile.IUNRESERVED : CharUtils.Profile.UNRESERVED)
                    : UrlEncoding.encode((Readable) val, "UTF-8",
                            context.isIri() ? CharUtils.Profile.RESERVEDANDIUNRESERVED
                                    : CharUtils.Profile.RESERVEDANDUNRESERVED);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else if (val instanceof CharSequence) {
        val = trim(normalize((CharSequence) val), len);
        return encode((CharSequence) val, context.isIri(), reserved);
    } else if (val instanceof Byte) {
        return UrlEncoding.encode(((Byte) val).byteValue());
    } else if (val instanceof Context) {
        StringBuilder buf = new StringBuilder();
        Context ctx = (Context) val;
        for (String name : ctx) {
            String _val = toString(ctx.resolve(name), context, reserved, false, null, null, len);
            appendif(buf.length() > 0, buf, exp);
            buf.append(name).append(explode ? '=' : ',').append(_val);
        }
        return buf.toString();
    } else if (val instanceof Iterable) {
        StringBuilder buf = new StringBuilder();
        for (Object obj : (Iterable<Object>) val) {
            appendif(buf.length() > 0, buf, exp);
            appendif(explode && explodePfx != null, buf, explodePfx);
            buf.append(toString(obj, context, reserved, false, null, null, len));
        }
        return buf.toString();
    } else if (val instanceof Iterator) {
        StringBuilder buf = new StringBuilder();
        Iterator<Object> i = (Iterator<Object>) val;
        while (i.hasNext()) {
            Object obj = i.next();
            appendif(buf.length() > 0, buf, exp);
            appendif(explode && explodePfx != null, buf, explodePfx);
            buf.append(toString(obj, context, reserved, false, null, null, len));
        }
        return buf.toString();
    } else if (val instanceof Enumeration) {
        StringBuilder buf = new StringBuilder();
        Enumeration<Object> i = (Enumeration<Object>) val;
        while (i.hasMoreElements()) {
            Object obj = i.nextElement();
            appendif(buf.length() > 0, buf, exp);
            appendif(explode && explodePfx != null, buf, explodePfx);
            buf.append(toString(obj, context, reserved, false, null, null, len));
        }
        return buf.toString();
    } else if (val instanceof Map) {
        StringBuilder buf = new StringBuilder();
        Map<Object, Object> map = (Map<Object, Object>) val;
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            String _key = toString(entry.getKey(), context, reserved, false, null, null, len);
            String _val = toString(entry.getValue(), context, reserved, false, null, null, len);
            appendif(buf.length() > 0, buf, exp);
            buf.append(_key).append(explode ? '=' : ',').append(_val);
        }
        return buf.toString();
    } else if (val instanceof Supplier) {
        return toString(((Supplier<?>) val).get(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Optional) {
        Optional<?> o = (Optional<?>) val;
        return toString(o.orNull(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Multimap) {
        Multimap<?, ?> mm = (Multimap<?, ?>) val;
        return toString(mm.asMap(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Callable) {
        Callable<Object> callable = (Callable<Object>) val;
        try {
            return toString(callable.call(), context, reserved, explode, explodeDelim, explodePfx, len);
        } catch (Exception e) {
            throw ExceptionHelper.propogate(e);
        }
    } else if (val instanceof Reference) {
        Reference<Object> ref = (Reference<Object>) val;
        return toString(ref.get(), context, reserved, explode, explodeDelim, explodePfx, len);
    } else if (val instanceof Future) {
        try {
            Future<Object> future = (Future<Object>) val;
            return toString(future.get(), context, reserved, explode, explodeDelim, explodePfx, len);
        } catch (Throwable e) {
            throw ExceptionHelper.propogate(e);
        }
    } else {
        if (val != null)
            val = normalize(val.toString());
        return encode(val != null ? val.toString() : null, context.isIri(), reserved);
    }
}

From source file:com.twitter.aurora.scheduler.http.SchedulerzJob.java

private static Map<String, SchedulingDetails> buildSchedulingTable(Iterable<IAssignedTask> tasks) {

    Map<Integer, ITaskConfig> byInstance = Maps
            .transformValues(Maps.uniqueIndex(tasks, Tasks.ASSIGNED_TO_INSTANCE_ID), Tasks.ASSIGNED_TO_INFO);
    Map<Integer, SchedulingDetails> detailsByInstance = Maps.transformValues(byInstance, CONFIG_TO_DETAILS);
    Multimap<SchedulingDetails, Integer> instancesByDetails = Multimaps
            .invertFrom(Multimaps.forMap(detailsByInstance), HashMultimap.<SchedulingDetails, Integer>create());
    Map<SchedulingDetails, String> instanceStringsByDetails = Maps.transformValues(instancesByDetails.asMap(),
            TransformationUtils.INSTANCES_TOSTRING);
    return HashBiMap.create(instanceStringsByDetails).inverse();
}

From source file:org.apache.samza.execution.ExecutionPlanner.java

/**
 * Fetch the partitions of source/sink streams and update the StreamEdges.
 * @param jobGraph {@link JobGraph}//from w w  w . java2 s . com
 * @param streamManager the {@link StreamManager} to interface with the streams.
 */
/* package private */ static void updateExistingPartitions(JobGraph jobGraph, StreamManager streamManager) {
    Set<StreamEdge> existingStreams = new HashSet<>();
    existingStreams.addAll(jobGraph.getSources());
    existingStreams.addAll(jobGraph.getSinks());

    Multimap<String, StreamEdge> systemToStreamEdges = HashMultimap.create();
    // group the StreamEdge(s) based on the system name
    existingStreams.forEach(streamEdge -> {
        SystemStream systemStream = streamEdge.getSystemStream();
        systemToStreamEdges.put(systemStream.getSystem(), streamEdge);
    });
    for (Map.Entry<String, Collection<StreamEdge>> entry : systemToStreamEdges.asMap().entrySet()) {
        String systemName = entry.getKey();
        Collection<StreamEdge> streamEdges = entry.getValue();
        Map<String, StreamEdge> streamToStreamEdge = new HashMap<>();
        // create the stream name to StreamEdge mapping for this system
        streamEdges.forEach(
                streamEdge -> streamToStreamEdge.put(streamEdge.getSystemStream().getStream(), streamEdge));
        // retrieve the partition counts for the streams in this system
        Map<String, Integer> streamToPartitionCount = streamManager.getStreamPartitionCounts(systemName,
                streamToStreamEdge.keySet());
        // set the partitions of a stream to its StreamEdge
        streamToPartitionCount.forEach((stream, partitionCount) -> {
            streamToStreamEdge.get(stream).setPartitionCount(partitionCount);
            log.debug("Partition count is {} for stream {}", partitionCount, stream);
        });
    }
}