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

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

Introduction

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

Prototype

@Beta
public static <K, V> Map<K, Collection<V>> asMap(Multimap<K, V> multimap) 

Source Link

Document

Returns Multimap#asMap multimap.asMap() .

Usage

From source file:com.b2international.snowowl.core.compare.CompareResultsDsvExporter.java

public File export(IProgressMonitor monitor) throws IOException {

    CsvMapper mapper = new CsvMapper();
    CsvSchema schema = mapper.schemaFor(CompareData.class).withColumnSeparator(delimiter).withHeader().sortedBy(
            "componentType", "componentId", "componentType", "label", "changeKind", "attribute", "from", "to");

    try (SequenceWriter writer = mapper.writer(schema).writeValues(outputPath.toFile())) {
        monitor.beginTask("Exporting compare results to DSV", compareResults.getTotalNew()
                + compareResults.getTotalChanged() + compareResults.getTotalDeleted());

        ListMultimap<Short, ComponentIdentifier> newComponentIdentifiers = Multimaps
                .index(compareResults.getNewComponents(), ComponentIdentifier::getTerminologyComponentId);
        ListMultimap<Short, String> newComponentIds = ImmutableListMultimap.copyOf(
                Multimaps.transformValues(newComponentIdentifiers, ComponentIdentifier::getComponentId));

        for (short terminologyComponentId : newComponentIds.keySet()) {
            for (List<String> componentIds : Lists.partition(newComponentIds.get(terminologyComponentId),
                    PARTITION_SIZE)) {//from w ww.j  ava  2  s.co  m
                RevisionIndexRequestBuilder<CollectionResource<IComponent>> componentFetchRequest = fetcherFunction
                        .apply(terminologyComponentId, componentIds);

                if (componentFetchRequest == null) {
                    break;
                }

                CollectionResource<IComponent> components = componentFetchRequest
                        .build(repositoryUuid, compareBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync();

                for (IComponent component : components) {
                    writer.write(new CompareData(component, ChangeKind.ADDED));
                }

                monitor.worked(components.getItems().size());
            }
        }

        ListMultimap<Short, ComponentIdentifier> changedComponentIdentifiers = Multimaps
                .index(compareResults.getChangedComponents(), ComponentIdentifier::getTerminologyComponentId);
        ListMultimap<Short, String> changedComponentIds = ImmutableListMultimap.copyOf(
                Multimaps.transformValues(changedComponentIdentifiers, ComponentIdentifier::getComponentId));
        ListMultimap<String, IComponent> componentPairs = ArrayListMultimap.create(PARTITION_SIZE, 2);

        for (short terminologyComponentId : changedComponentIds.keySet()) {
            for (List<String> componentIds : Lists.partition(changedComponentIds.get(terminologyComponentId),
                    PARTITION_SIZE)) {
                componentPairs.clear();
                RevisionIndexRequestBuilder<CollectionResource<IComponent>> componentFetchRequest = fetcherFunction
                        .apply(terminologyComponentId, componentIds);

                if (componentFetchRequest == null) {
                    break;
                }

                componentFetchRequest.build(repositoryUuid, baseBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync()
                        .forEach(c -> componentPairs.put(c.getId(), c));

                componentFetchRequest.build(repositoryUuid, compareBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync()
                        .forEach(c -> componentPairs.put(c.getId(), c));

                for (Entry<String, List<IComponent>> entry : Multimaps.asMap(componentPairs).entrySet()) {
                    IComponent baseComponent = entry.getValue().get(0);
                    IComponent compareComponent = entry.getValue().get(1);
                    Collection<CompareData> compareResults = getCompareResultsOfComponent.apply(baseComponent,
                            compareComponent);

                    for (CompareData d : compareResults) {
                        writer.write(d);
                    }
                }

                monitor.worked(componentPairs.keySet().size());
            }
        }

        ListMultimap<Short, ComponentIdentifier> deletedComponentIdentifiers = Multimaps
                .index(compareResults.getDeletedComponents(), ComponentIdentifier::getTerminologyComponentId);
        ListMultimap<Short, String> deletedComponentIds = ImmutableListMultimap.copyOf(
                Multimaps.transformValues(deletedComponentIdentifiers, ComponentIdentifier::getComponentId));

        for (short terminologyComponentId : deletedComponentIds.keySet()) {
            for (List<String> componentIds : Lists.partition(deletedComponentIds.get(terminologyComponentId),
                    PARTITION_SIZE)) {
                RevisionIndexRequestBuilder<CollectionResource<IComponent>> componentFetchRequest = fetcherFunction
                        .apply(terminologyComponentId, componentIds);

                if (componentFetchRequest == null) {
                    break;
                }

                CollectionResource<IComponent> components = componentFetchRequest
                        .build(repositoryUuid, baseBranch)
                        .execute(ApplicationContext.getServiceForClass(IEventBus.class)).getSync();

                for (IComponent component : components) {
                    writer.write(new CompareData(component, ChangeKind.DELETED));
                }

                monitor.worked(components.getItems().size());
            }
        }

    } finally {
        monitor.done();
    }

    return outputPath.toFile();
}

From source file:de.bund.bfr.knime.nls.NlsUtils.java

public static Map<String, List<Double>> getDiffVariableValues(BufferedDataTable table, String id, Function f) {
    ListMultimap<String, Double> values = ArrayListMultimap.create();

    for (DataRow row : getRowsById(table, id)) {
        Double time = IO.getDouble(row.getCell(table.getSpec().findColumnIndex(f.getTimeVariable())));
        Double target = IO.getDouble(row.getCell(table.getSpec().findColumnIndex(f.getDependentVariable())));

        if (time != null && target != null && Double.isFinite(time) && Double.isFinite(target)) {
            values.put(f.getTimeVariable(), time);
            values.put(f.getDependentVariable(), target);
        }//from   w  ww .j  a va 2  s .  c om

    }

    return Multimaps.asMap(values);
}

From source file:dagger.internal.codegen.MapMultibindingValidator.java

private String inconsistentMapKeyAnnotationTypesErrorMessage(
        ImmutableSetMultimap<Equivalence.Wrapper<DeclaredType>, ContributionBinding> contributionsByMapKeyAnnotationType,
        Key mapBindingKey) {//w w w .  j  a  v  a  2  s  .co m
    StringBuilder message = new StringBuilder(mapBindingKey.toString())
            .append(" uses more than one @MapKey annotation type");
    Multimaps.asMap(contributionsByMapKeyAnnotationType).forEach((annotationType, contributions) -> {
        message.append('\n').append(INDENT).append(annotationType.get()).append(':');
        bindingDeclarationFormatter.formatIndentedList(message, contributions, 2);
    });
    return message.toString();
}

From source file:de.bund.bfr.knime.gis.views.canvas.CanvasUtils.java

public static <V extends Node> Map<Edge<V>, Set<Edge<V>>> joinEdges(Collection<Edge<V>> edges,
        EdgePropertySchema schema, Collection<Edge<V>> allEdges) {
    SetMultimap<Pair<V, V>, Edge<V>> edgeMap = LinkedHashMultimap.create();

    for (Edge<V> edge : edges) {
        edgeMap.put(new Pair<>(edge.getFrom(), edge.getTo()), edge);
    }/*ww w . java2 s  . com*/

    Map<Edge<V>, Set<Edge<V>>> joined = new LinkedHashMap<>();
    Set<String> usedIds = CanvasUtils.getElementIds(allEdges);

    Multimaps.asMap(edgeMap).forEach((endpoints, edgesInBetween) -> {
        Map<String, Object> properties = new LinkedHashMap<>();

        for (Edge<V> edge : edgesInBetween) {
            CanvasUtils.addMapToMap(properties, schema, edge.getProperties());
        }

        V from = endpoints.getFirst();
        V to = endpoints.getSecond();
        String id = KnimeUtils.createNewValue(from.getId() + "->" + to.getId(), usedIds);

        usedIds.add(id);
        properties.put(schema.getId(), id);
        properties.put(schema.getFrom(), from.getId());
        properties.put(schema.getTo(), to.getId());
        joined.put(new Edge<>(id, properties, from, to), edgesInBetween);
    });

    return joined;
}

From source file:org.sonar.java.se.Expectations.java

private Map<ImmutableList<Integer>, String> computeFlowLines() {
    Map<String, SortedSet<FlowComment>> flows = Multimaps.asMap(this.flows);
    return flows.entrySet().stream().collect(Collectors
            .toMap(e -> flowToLines(e.getValue(), flowComment -> flowComment.line), Map.Entry::getKey));
}

From source file:com.facebook.presto.raptor.storage.ShardCompactionManager.java

private void discoverShards() {
    if (shardsInProgress.size() >= MAX_PENDING_COMPACTIONS) {
        return;/*from ww  w.  j  a  va 2 s  .  c o m*/
    }

    Set<ShardMetadata> allShards = shardManager.getNodeShards(currentNodeIdentifier);
    ListMultimap<Long, ShardMetadata> tableShards = Multimaps.index(allShards, ShardMetadata::getTableId);

    for (Entry<Long, List<ShardMetadata>> entry : Multimaps.asMap(tableShards).entrySet()) {
        long tableId = entry.getKey();
        if (!metadataDao.isCompactionEnabled(tableId)) {
            continue;
        }
        List<ShardMetadata> shardMetadata = entry.getValue();

        Set<ShardMetadata> shards = shardMetadata.stream().filter(this::needsCompaction)
                .filter(shard -> !shardsInProgress.contains(shard.getShardUuid())).collect(toSet());

        if (shards.size() <= 1) {
            continue;
        }

        Long temporalColumnId = metadataDao.getTemporalColumnId(tableId);
        CompactionSetCreator compactionSetCreator;
        if (temporalColumnId == null) {
            compactionSetCreator = new FileCompactionSetCreator(maxShardSize, maxShardRows);
        } else {
            Type type = metadataDao.getTableColumn(tableId, temporalColumnId).getDataType();
            compactionSetCreator = new TemporalCompactionSetCreator(maxShardSize, maxShardRows, type);
            shards = filterShardsWithTemporalMetadata(shardMetadata, tableId, temporalColumnId);
        }
        addToCompactionQueue(compactionSetCreator, tableId, shards);
    }
}

From source file:com.tinspx.util.net.Headers.java

/**
 * Returns a modifiable {@code Map} view of the headers. Note that this map
 * is acquired through {@link Multimap#asMap()}, and therefore the map does
 * not support {@code put} or {@code putAll}, nor do its entries support
 * {@link java.util.Map.Entry#setValue(Object) setValue}.
 *///from   ww w .  j  a v  a 2 s  .  c  o  m
public Map<String, List<String>> asMap() {
    return Multimaps.asMap(view());
}

From source file:org.rakam.presto.stream.metadata.StreamMetadata.java

@Override
public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session,
        SchemaTablePrefix prefix) {//  w w  w.j  a v a2  s .c o  m
    checkNotNull(prefix, "prefix is null");

    ImmutableListMultimap.Builder<SchemaTableName, ColumnMetadata> columns = ImmutableListMultimap.builder();
    for (TableColumn tableColumn : dao.listTableColumns(connectorId, prefix.getSchemaName(),
            prefix.getTableName())) {
        ColumnMetadata columnMetadata = new ColumnMetadata(tableColumn.getColumnName(),
                tableColumn.getDataType(), tableColumn.getOrdinalPosition(), false);
        columns.put(tableColumn.getTable(), columnMetadata);
    }
    return Multimaps.asMap(columns.build());
}

From source file:org.onosproject.incubator.net.neighbour.impl.NeighbourResolutionManager.java

@Override
public Map<ConnectPoint, Collection<NeighbourHandlerRegistration>> getHandlerRegistrations() {
    return ImmutableMap.copyOf(Multimaps.asMap(packetHandlers));
}

From source file:de.bund.bfr.knime.openkrise.common.DeliveryUtils.java

private static void checkAmounts(Map<String, Delivery> deliveries, SetMultimap<String, String> warnings) {
     SetMultimap<String, Delivery> deliveriesByLot = LinkedHashMultimap.create();

     for (Delivery d : deliveries.values()) {
         deliveriesByLot.put(d.getLotNumber(), d);
     }/*from  w  w w .  j  av  a2 s.  c o  m*/

     for (Map.Entry<String, Set<Delivery>> lot : Multimaps.asMap(deliveriesByLot).entrySet()) {
         Set<String> ingredients = new LinkedHashSet<>();
         Double kgOut = 0.0;
         Double amountOut = 0.0;
         String unitOut = null;

         for (Delivery d : lot.getValue()) {
             ingredients = d.getAllPreviousIds();

             if (kgOut != null) {
                 if (d.getAmountInKg() != null) {
                     kgOut += d.getAmountInKg();
                 } else {
                     kgOut = null;
                 }
             }

             if (amountOut != null) {
                 if (d.getAmount() != null && d.getUnit() != null
                         && (unitOut == null || unitOut.equals(d.getUnit()))) {
                     amountOut += d.getAmount();
                     unitOut = d.getUnit();
                 } else {
                     amountOut = null;
                 }
             }
         }

         if (ingredients.isEmpty()) {
             continue;
         }

         Double kgIn = 0.0;
         Double amountIn = 0.0;
         String unitIn = null;

         for (String prev : ingredients) {
             Delivery d = deliveries.get(prev);

             if (kgIn != null) {
                 if (d.getAmountInKg() != null) {
                     kgIn += d.getAmountInKg();
                 } else {
                     kgIn = null;
                 }
             }

             if (amountIn != null) {
                 if (d.getAmount() != null && d.getUnit() != null
                         && (unitIn == null || unitIn.equals(d.getUnit()))) {
                     amountIn += d.getAmount();
                     unitIn = d.getUnit();
                 } else {
                     amountIn = null;
                 }
             }
         }

         if (amountIn != null && unitIn != null && amountOut != null && unitOut != null && unitIn.equals(unitOut)
                 && areTooDifferent(amountIn, amountOut)) {
             warnings.put(AMOUNTS_INCORRECT, "Lot=" + lot.getKey() + ": In=" + amountIn + " vs. Out=" + amountOut
                     + " (" + unitOut + ")");
         } else if (kgIn != null && kgOut != null && areTooDifferent(kgIn, kgOut)) {
             warnings.put(AMOUNTS_INCORRECT,
                     "Lot=" + lot.getKey() + ": In=" + kgIn + "kg vs. Out=" + kgOut + "kg");
         }
     }
 }