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

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

Introduction

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

Prototype

@Override
@GwtIncompatible("NavigableMap")
public NavigableMap<K, Collection<V>> asMap() 

Source Link

Document

Because a TreeMultimap has unique sorted keys, this method returns a NavigableMap , instead of the java.util.Map specified in the Multimap interface.

Usage

From source file:org.onosproject.cli.MetricsListCommand.java

@Override
protected void execute() {
    MetricsService metricsService = get(MetricsService.class);

    MetricFilter filter = metricName != null ? (name, metric) -> name.equals(metricName) : MetricFilter.ALL;

    TreeMultimap<String, Metric> matched = listMetrics(metricsService, filter);
    matched.asMap().forEach((name, metrics) -> {
        for (Metric metric : metrics) {
            printMetric(name, metric);//from   w  w  w  . j  a v  a 2  s.  c om
        }
    });
}

From source file:org.onosproject.rest.resources.MetricsWebResource.java

/**
 * Gets stats information of a metric. Returns array of all information for the
 * specified metric.//ww w. j  a va  2  s  . co  m
 *
 * @param metricName metric name
 * @return 200 OK with metric information as array
 * @onos.rsModel Metric
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{metricName}")
public Response getMetricByName(@PathParam("metricName") String metricName) {
    ObjectNode metricNode = root.putObject("metric");
    MetricFilter filter = metricName != null ? (name, metric) -> name.equals(metricName) : MetricFilter.ALL;
    TreeMultimap<String, Metric> matched = listMetrics(service, filter);

    if (matched.isEmpty()) {
        throw new ItemNotFoundException(E_METRIC_NAME_NOT_FOUND);
    }

    matched.asMap().get(metricName).forEach(m -> {
        metricNode.set(metricName, codec(Metric.class).encode(m, this));
    });

    return ok(root).build();
}

From source file:hihex.cs.LogFiles.java

public void removeExpired(final Preferences preferences) {
    long purgeDuration = preferences.getPurgeDuration();
    long purgeFilesize = preferences.getPurgeFilesize();

    final TreeMultimap<Long, File> files = list();

    // Don't use `TreeMultimap.create(files)`! The key comparator will be reverted to the natural one.
    final TreeMultimap<Long, File> filesToKeep = TreeMultimap.create(Ordering.natural().reverse(),
            Ordering.natural());//from w  w  w  .  jav  a  2  s  . c o m
    filesToKeep.putAll(files);

    if (purgeDuration >= 0) {
        final long expireDate = System.currentTimeMillis() - purgeDuration;
        filesToKeep.asMap().tailMap(expireDate).clear();
    }

    if (purgeFilesize >= 0) {
        final Iterator<File> iterator = filesToKeep.values().iterator();
        long currentFilesize = 0;
        while (iterator.hasNext()) {
            final File file = iterator.next();
            if (currentFilesize > purgeFilesize) {
                iterator.remove();
            } else {
                currentFilesize += file.length();
            }
        }
    }

    files.entries().removeAll(filesToKeep.entries());
    for (final File file : files.values()) {
        file.delete();
    }
}

From source file:org.apache.calcite.util.EquivalenceSet.java

/** Returns a map of the canonical element in each equivalence class to the
 * set of elements in that class. The keys are sorted in natural order, as
 * are the elements within each key. */
public SortedMap<E, SortedSet<E>> map() {
    final TreeMultimap<E, E> multimap = TreeMultimap.create();
    for (Map.Entry<E, E> entry : parents.entrySet()) {
        multimap.put(entry.getValue(), entry.getKey());
    }/*from  ww w  .j a v a  2s. c  om*/
    // Create an immutable copy. Keys and values remain in sorted order.
    final ImmutableSortedMap.Builder<E, SortedSet<E>> builder = ImmutableSortedMap.naturalOrder();
    for (Map.Entry<E, Collection<E>> entry : multimap.asMap().entrySet()) {
        builder.put(entry.getKey(), ImmutableSortedSet.copyOf(entry.getValue()));
    }
    return builder.build();
}

From source file:co.cask.cdap.internal.app.runtime.adapter.PluginRepository.java

/**
 * Returns a {@link SortedMap} of all plugins available for the given application template. The keys
 * are sorted by the {@link PluginInfo}. Only unique {@link PluginClass} are returned in the value
 * Collection, where uniqueness is determined by the plugin class type and name only.
 *
 * @param template name of the template/* ww  w . jav a  2  s.  c  o  m*/
 */
public SortedMap<PluginInfo, Collection<PluginClass>> getPlugins(String template) {
    TreeMultimap<PluginInfo, PluginClass> result = plugins.get().get(template);
    return result == null ? ImmutableSortedMap.<PluginInfo, Collection<PluginClass>>of()
            : Collections.unmodifiableSortedMap(result.asMap());
}

From source file:com.publictransitanalytics.scoregenerator.environment.StoredGrid.java

private static ImmutableSetMultimap<GridPoint, Sector> dispositionSectors(
        final NavigableSet<GeoLatitude> latitudeGridlines,
        final ImmutableSetMultimap<GeoLatitude, GridPoint> latitudePointMap,
        final NavigableSet<GeoLongitude> longitudeGridlines,
        final ImmutableSetMultimap<GeoLongitude, GridPoint> longitudePointMap,
        TreeBasedTable<GeoLatitude, GeoLongitude, Sector> sectorTable) throws InterruptedException {
    final ImmutableSetMultimap.Builder<GridPoint, Sector> pointSectorMapBuilder = ImmutableSetMultimap
            .builder();// w w w  . j  av  a 2  s  .  com

    final Iterator<GeoLongitude> longitudeIterator = longitudeGridlines.iterator();

    final GeoLongitude firstLongitude = longitudeIterator.next();
    GeoLongitude longitude = firstLongitude;
    TreeMultimap<GeoLatitude, GridPoint> latitudeSortedPoints = getLatitudeSortedPointsForLongitude(longitude,
            longitudePointMap);

    while (longitudeIterator.hasNext()) {
        final GeoLongitude nextLongitude = longitudeIterator.next();
        final TreeMultimap<GeoLatitude, GridPoint> nextLatitudeSortedPoints = getLatitudeSortedPointsForLongitude(
                nextLongitude, longitudePointMap);

        final Iterator<GeoLatitude> latitudeIterator = latitudeGridlines.iterator();

        final GeoLatitude firstLatitude = latitudeIterator.next();
        GeoLatitude latitude = firstLatitude;
        TreeMultimap<GeoLongitude, GridPoint> longitudeSortedPoints = getLongitudeSortedPointsForLatitude(
                latitude, latitudePointMap);

        while (latitudeIterator.hasNext()) {
            final GeoLatitude nextLatitude = latitudeIterator.next();
            final TreeMultimap<GeoLongitude, GridPoint> nextLongitudeSortedPoints = getLongitudeSortedPointsForLatitude(
                    nextLatitude, latitudePointMap);

            final Sector sector = sectorTable.get(latitude, longitude);

            if (sector != null) {

                final Set<GridPoint> filteredLatitudePoints = latitudeSortedPoints.asMap()
                        .subMap(latitude, true, nextLatitude, true).values().stream()
                        .flatMap(Collection::stream).collect(Collectors.toSet());
                for (final GridPoint point : filteredLatitudePoints) {
                    pointSectorMapBuilder.put(point, sector);
                }

                final Set<GridPoint> filteredNextLatitudePoints = nextLatitudeSortedPoints.asMap()
                        .subMap(latitude, true, nextLatitude, true).values().stream()
                        .flatMap(Collection::stream).collect(Collectors.toSet());
                for (final GridPoint point : filteredNextLatitudePoints) {
                    pointSectorMapBuilder.put(point, sector);
                }

                final Set<GridPoint> filteredLongitudePoints = longitudeSortedPoints.asMap()
                        .subMap(longitude, true, nextLongitude, true).values().stream()
                        .flatMap(Collection::stream).collect(Collectors.toSet());
                for (final GridPoint point : filteredLongitudePoints) {
                    pointSectorMapBuilder.put(point, sector);
                }

                final Set<GridPoint> filteredNextLongitudePoints = nextLongitudeSortedPoints.asMap()
                        .subMap(longitude, true, nextLongitude, true).values().stream()
                        .flatMap(Collection::stream).collect(Collectors.toSet());
                for (final GridPoint point : filteredNextLongitudePoints) {
                    pointSectorMapBuilder.put(point, sector);
                }

            }

            latitude = nextLatitude;
            longitudeSortedPoints = nextLongitudeSortedPoints;
        }

        longitude = nextLongitude;
        latitudeSortedPoints = nextLatitudeSortedPoints;
    }

    return pointSectorMapBuilder.build();
}

From source file:de.hzi.helmholtz.Compare.PathwayComparisonUsingModules.java

public Map<String, Map<String, Double>> pathwayComparisonCoalesce(PathwayUsingModules newSource,
        PathwayUsingModules newTarget, BiMap<String, Integer> newSourceGeneIdToPositionMap,
        BiMap<String, Integer> newTargetGeneIdToPositionMap) {

    Multimap<Integer, Multimap<Double, String>> forward = pcompare(newSource, newTarget); // key: qgeneId, value: {score=tgenecombination;...}
    Multimap<Integer, Multimap<Double, String>> reverse = pcompare(newTarget, newSource);

    // Re-construct the bimaps
    newSourceGeneIdToPositionMap = HashBiMap.create();
    int temp = 0;
    for (Module e : newSource.getModules()) {
        newSourceGeneIdToPositionMap.put(e.getModuleId(), temp++);
    }//from   www.  j av a 2s  .c  om
    newTargetGeneIdToPositionMap = HashBiMap.create();
    temp = 0;
    for (Module e : newTarget.getModules()) {
        newTargetGeneIdToPositionMap.put(e.getModuleId(), temp++);
    }

    /* Create global list of matchings ordered by score by joining forward and reverse lists
     * key: querygene -> targetgenes
     * value: score
     */
    TreeMultimap<Double, String> globalMap = TreeMultimap.create(Ordering.natural().reverse(),
            Ordering.natural());
    for (Map.Entry<Integer, Multimap<Double, String>> e : forward.entries()) {
        int fgene = e.getKey();
        Multimap<Double, String> geneAndScore = e.getValue();
        for (Map.Entry<Double, String> scoreEntry : geneAndScore.entries()) {
            double score = scoreEntry.getKey();
            String matchingGeneString = scoreEntry.getValue();
            String[] multipleMatchingGenes = matchingGeneString.split(",");
            for (String matchingGene : multipleMatchingGenes) {
                String newKey = fgene + "->" + matchingGene;
                globalMap.put(score, newKey);
            }
        }
    }
    for (Map.Entry<Integer, Multimap<Double, String>> e : reverse.entries()) {
        int rgene = e.getKey();
        Multimap<Double, String> geneAndScore = e.getValue();
        for (Map.Entry<Double, String> scoreEntry : geneAndScore.entries()) {
            double score = scoreEntry.getKey();
            String matchingGeneString = scoreEntry.getValue();
            String[] multipleMatchingGenes = matchingGeneString.split(",");
            for (String matchingGene : multipleMatchingGenes) {
                String newKey = matchingGene + "->" + rgene;
                globalMap.put(score, newKey);
            }
        }
    }
    //////System.out.println("----------------------------------------------------------------------------------------------------------------------------------");
    // create alignment
    // ////System.out.println(globalMap);
    Map<String, Double> matchingInTarget;
    Set<String> queryGenesCovered = new HashSet<String>();
    Set<String> targetGenesCovered = new HashSet<String>();
    Map<String, Map<String, Double>> currentBestResultMapping = new TreeMap<String, Map<String, Double>>();
    for (Map.Entry<Double, String> entry : globalMap.entries()) {
        double score = entry.getKey();
        //score=[alignment1, aligment2, ..]
        String alignment = entry.getValue();
        int i = 100;
        for (String collection : globalMap.asMap().get(score)) {
            int count = collection.length() - collection.replace("+", "").length();
            if (i > count) {
                i = count;
                alignment = collection;
            }
        }
        String bestScoreAlignment = alignment.split(",")[0];
        // start->end
        String start = bestScoreAlignment.split("->")[0];
        String end = bestScoreAlignment.split("->")[1];

        // start and end can be combination of genes
        Set<String> s = new HashSet<String>(Arrays.asList((start + "+").split("\\+")));
        Set<String> t = new HashSet<String>(Arrays.asList((end + "+").split("\\+")));

        // add to result mapping
        Set<String> sIntersection = new HashSet<String>();
        sIntersection.addAll(queryGenesCovered);
        sIntersection.retainAll(s);

        Set<String> tIntersection = new HashSet<String>();
        tIntersection.addAll(targetGenesCovered);
        tIntersection.retainAll(t);

        if (sIntersection.isEmpty() && tIntersection.isEmpty()) {
            matchingInTarget = new HashMap<String, Double>();
            matchingInTarget.put(reconstructWithGeneId(end, newTargetGeneIdToPositionMap), score);
            currentBestResultMapping.put(reconstructWithGeneId(start, newSourceGeneIdToPositionMap),
                    matchingInTarget);
            queryGenesCovered.addAll(s);
            targetGenesCovered.addAll(t);
            break;
        }
    }
    return currentBestResultMapping;
}