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

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

Introduction

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

Prototype

public static <K, V> TreeMultimap<K, V> create(Comparator<? super K> keyComparator,
        Comparator<? super V> valueComparator) 

Source Link

Document

Creates an empty TreeMultimap instance using explicit comparators.

Usage

From source file:de.anycook.recommendation.Recommendation.java

public static List<Recipe> recommend(int userId) throws SQLException {
    try (DBRecommend dbrecommend = new DBRecommend()) {
        Map<String, Integer> tasteTags = dbrecommend.getTastyTags(userId);
        Map<String, Collection<String>> recipes = dbrecommend.getRecipesByTags(userId);
        //logger.debug("tagRecipes: "+tagRecipes);

        // cos(a,b) = a*b/|a|*|b|
        SortedSetMultimap<Double, String> recommendMap = TreeMultimap.create(new InvertedComparator<Double>(),
                new StandardComparator<String>());
        double schmecktAmount = 0;
        for (String tag : tasteTags.keySet())
            schmecktAmount += Math.pow(tasteTags.get(tag), 2);
        schmecktAmount = Math.sqrt(schmecktAmount);

        for (String tagRecipe : recipes.keySet()) {
            double enumerator = 0;
            Collection<String> tags = recipes.get(tagRecipe);
            for (String tag : tags) {
                if (!tasteTags.containsKey(tag))
                    continue;
                enumerator += tasteTags.get(tag);
            }/*w  ww  .j  ava2  s  .  co  m*/

            double denominator = schmecktAmount * Math.sqrt(tags.size());
            double result = enumerator / denominator;
            recommendMap.put(result, tagRecipe);
        }

        List<Recipe> finalRecipes = new ArrayList<>();
        for (String name : recommendMap.values()) {
            try {
                finalRecipes.add(Recipe.init(name));
            } catch (DBRecipe.RecipeNotFoundException e) {
                //will never happen
            }
        }

        return finalRecipes;
    }
}

From source file:moavns.SolucaoAleatoria.java

public static Solucao VizinhoRedundancia(Solucao inicio) {
    Comparator comparador = new Comparador();
    Ordering<Float> ordenacao = Ordering.natural();
    Comparator ordenacao1 = ordenacao;
    Ordering<Solucao> ordenacao2 = Ordering.from(comparador);
    Multimap<Float, Solucao> novassolucoes = TreeMultimap.create(ordenacao1, ordenacao2);
    for (Integer entrada : inicio.getLinhasX().keySet()) {
        Solucao novasolucao = new Solucao(inicio);
        Coluna testar = inicio.getLinhasX().get(entrada);
        novasolucao.getColunas().add(testar);
        novasolucao.setCustototal(novasolucao.getCustototal() + testar.getCusto());
        Solucao solucaox = eliminarRedundancia(novasolucao);
        String stringsolucao = MOAVNS.transformaSolucao(solucaox);
        if (!MOAVNS.solucoes.contains(stringsolucao)) {
            return solucaox;
        }/*from  w  w  w. ja  va2  s  .  c  om*/
    }
    return inicio;
}

From source file:dmg.util.command.AnnotatedCommandUtils.java

/**
 * Returns the option fields grouped by category of a given command class.
 *///from  ww  w.  j a  v a 2 s.  c  o m
public static Multimap<String, Field> getOptionsByCategory(Class<?> clazz) {
    Multimap<String, Field> options = TreeMultimap.create(Ordering.natural(),
            Ordering.natural().onResultOf(GET_NAME));
    for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
        for (Field field : c.getDeclaredFields()) {
            Option option = field.getAnnotation(Option.class);
            if (option != null) {
                options.put(option.category(), field);
            }
            CommandLine cmd = field.getAnnotation(CommandLine.class);
            if (cmd != null) {
                options.put(cmd.category(), field);
            }
        }
    }
    return options;
}

From source file:com.publictransitanalytics.scoregenerator.output.ComparativeSectorReachInformation.java

private static Map<SimplePath, Integer> getPathCounts(final Set<MovementPath> bestPaths)
        throws InterruptedException {
    final Map<SimplePath, Integer> pathCounts;
    final TreeMultimap<Integer, SimplePath> frequencyMap = TreeMultimap.create(Integer::compareTo,
            (p1, p2) -> p1.toString().compareTo(p2.toString()));

    if (bestPaths != null) {
        final ImmutableMultiset.Builder<SimplePath> bestSimplePathsBuilder = ImmutableMultiset.builder();
        for (final MovementPath bestPath : bestPaths) {
            bestSimplePathsBuilder.add(new SimplePath(bestPath));
        }/* w  ww. ja v a 2  s  . co m*/
        final ImmutableMultiset<SimplePath> bestSimplePaths = bestSimplePathsBuilder.build();

        for (final SimplePath path : bestSimplePaths.elementSet()) {
            frequencyMap.put(bestSimplePaths.count(path), path);
        }

        pathCounts = new LinkedHashMap<>();
        for (final Integer frequency : frequencyMap.keySet().descendingSet()) {
            final NavigableSet<SimplePath> pathsForFrequency = frequencyMap.get(frequency);
            for (final SimplePath pathForFrequency : pathsForFrequency) {
                pathCounts.put(pathForFrequency, frequency);
            }
        }
    } else {
        pathCounts = null;
    }
    return pathCounts;
}

From source file:hihex.cs.LogFiles.java

public TreeMultimap<Long, File> list() {
    final File[] files = mLogFolder.listFiles();
    final TreeMultimap<Long, File> sortedFiles = TreeMultimap.create(Ordering.natural().reverse(),
            Ordering.natural());/*from  ww w .j  a  va 2s.c  o  m*/
    for (final File file : files) {
        sortedFiles.put(file.lastModified(), file);
    }
    return sortedFiles;
}

From source file:org.gradle.api.tasks.diagnostics.internal.AggregateMultiProjectTaskReportModel.java

public void build() {
    groups = TreeMultimap.create(new Comparator<String>() {
        public int compare(String string1, String string2) {
            return string1.compareToIgnoreCase(string2);
        }//from   w  ww. j  a  v  a  2 s.  c om
    }, new Comparator<TaskDetails>() {
        public int compare(TaskDetails task1, TaskDetails task2) {
            return task1.getPath().compareTo(task2.getPath());
        }
    });
    for (TaskReportModel project : projects) {
        for (String group : project.getGroups()) {
            for (final TaskDetails task : project.getTasksForGroup(group)) {
                groups.put(group, mergeTasksWithSameName ? new MergedTaskDetails(task) : task);
            }
        }
    }
}

From source file:com.google.cloud.dataflow.sdk.options.PipelineOptionsValidator.java

/**
 * Validates that the passed {@link PipelineOptions} conforms to all the validation criteria from
 * the passed in interface./* www . j  av  a  2 s  .  co  m*/
 *
 * <p>Note that the interface requested must conform to the validation criteria specified on
 * {@link PipelineOptions#as(Class)}.
 *
 * @param klass The interface to fetch validation criteria from.
 * @param options The {@link PipelineOptions} to validate.
 * @return The type
 */
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
    checkNotNull(klass);
    checkNotNull(options);
    checkArgument(Proxy.isProxyClass(options.getClass()));
    checkArgument(Proxy.getInvocationHandler(options) instanceof ProxyInvocationHandler);

    // Ensure the methods for T are registered on the ProxyInvocationHandler
    T asClassOptions = options.as(klass);

    ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(asClassOptions);

    SortedSetMultimap<String, Method> requiredGroups = TreeMultimap.create(Ordering.natural(),
            PipelineOptionsFactory.MethodNameComparator.INSTANCE);
    for (Method method : ReflectHelpers.getClosureOfMethodsOnInterface(klass)) {
        Required requiredAnnotation = method.getAnnotation(Validation.Required.class);
        if (requiredAnnotation != null) {
            if (requiredAnnotation.groups().length > 0) {
                for (String requiredGroup : requiredAnnotation.groups()) {
                    requiredGroups.put(requiredGroup, method);
                }
            } else {
                checkArgument(handler.invoke(asClassOptions, method, null) != null,
                        "Missing required value for [" + method + ", \"" + getDescription(method) + "\"]. ");
            }
        }
    }

    for (String requiredGroup : requiredGroups.keySet()) {
        if (!verifyGroup(handler, asClassOptions, requiredGroups.get(requiredGroup))) {
            throw new IllegalArgumentException("Missing required value for group [" + requiredGroup
                    + "]. At least one of the following properties "
                    + Collections2.transform(requiredGroups.get(requiredGroup), ReflectHelpers.METHOD_FORMATTER)
                    + " required. Run with --help=" + klass.getSimpleName() + " for more information.");
        }
    }

    return asClassOptions;
}

From source file:org.apache.beam.sdk.options.PipelineOptionsValidator.java

/**
 * Validates that the passed {@link PipelineOptions} conforms to all the validation criteria from
 * the passed in interface./*from  w w  w . ja  va2s  .co m*/
 *
 * <p>Note that the interface requested must conform to the validation criteria specified on
 * {@link PipelineOptions#as(Class)}.
 *
 * @param klass The interface to fetch validation criteria from.
 * @param options The {@link PipelineOptions} to validate.
 * @return The type
 */
public static <T extends PipelineOptions> T validate(Class<T> klass, PipelineOptions options) {
    checkNotNull(klass);
    checkNotNull(options);
    checkArgument(Proxy.isProxyClass(options.getClass()));
    checkArgument(Proxy.getInvocationHandler(options) instanceof ProxyInvocationHandler);

    // Ensure the methods for T are registered on the ProxyInvocationHandler
    T asClassOptions = options.as(klass);

    ProxyInvocationHandler handler = (ProxyInvocationHandler) Proxy.getInvocationHandler(asClassOptions);

    SortedSetMultimap<String, Method> requiredGroups = TreeMultimap.create(Ordering.natural(),
            PipelineOptionsFactory.MethodNameComparator.INSTANCE);
    for (Method method : ReflectHelpers.getClosureOfMethodsOnInterface(klass)) {
        Required requiredAnnotation = method.getAnnotation(Validation.Required.class);
        if (requiredAnnotation != null) {
            if (requiredAnnotation.groups().length > 0) {
                for (String requiredGroup : requiredAnnotation.groups()) {
                    requiredGroups.put(requiredGroup, method);
                }
            } else {
                checkArgument(handler.invoke(asClassOptions, method, null) != null,
                        "Missing required value for [%s, \"%s\"]. ", method, getDescription(method));
            }
        }
    }

    for (String requiredGroup : requiredGroups.keySet()) {
        if (!verifyGroup(handler, asClassOptions, requiredGroups.get(requiredGroup))) {
            throw new IllegalArgumentException("Missing required value for group [" + requiredGroup
                    + "]. At least one of the following properties "
                    + Collections2.transform(requiredGroups.get(requiredGroup), ReflectHelpers.METHOD_FORMATTER)
                    + " required. Run with --help=" + klass.getSimpleName() + " for more information.");
        }
    }

    return asClassOptions;
}

From source file:streaming.operators.HashtagCounter.java

public void finish() throws Exception {
    TreeMultimap<Integer, String> map = TreeMultimap.create(Ordering.natural().reverse(),
            Ordering.natural().reverse());

    for (Entry<String, Integer> e : hashtagCounterMap.entrySet()) {
        map.put(e.getValue(), e.getKey());
    }/*w  w  w.  j av a2  s.c  o  m*/

    Set<Entry<Integer, String>> entries = map.entries();
    for (Entry<Integer, String> e : entries) {
        System.out.println(e.getValue() + " = " + e.getKey());
    }

}

From source file:com.publictransitanalytics.scoregenerator.output.SectorReachInformation.java

public SectorReachInformation(final Set<MovementPath> bestPaths, final int count,
        final Set<LocalDateTime> reachTimes) throws InterruptedException {

    reachCount = count;/*from  ww w . j  ava 2s  .c  om*/
    this.reachTimes = reachTimes.stream().map(time -> time.toLocalTime().toString())
            .collect(Collectors.toSet());

    final TreeMultimap<Integer, SimplePath> frequencyMap = TreeMultimap.create(Integer::compareTo,
            (p1, p2) -> p1.toString().compareTo(p2.toString()));

    if (bestPaths != null) {
        final ImmutableMultiset.Builder<SimplePath> bestSimplePathsBuilder = ImmutableMultiset.builder();
        for (final MovementPath bestPath : bestPaths) {
            bestSimplePathsBuilder.add(new SimplePath(bestPath));
        }
        final ImmutableMultiset<SimplePath> bestSimplePaths = bestSimplePathsBuilder.build();

        for (final SimplePath path : bestSimplePaths.elementSet()) {
            frequencyMap.put(bestSimplePaths.count(path), path);
        }

        pathCounts = new LinkedHashMap<>();
        for (final Integer frequency : frequencyMap.keySet().descendingSet()) {
            final NavigableSet<SimplePath> pathsForFrequency = frequencyMap.get(frequency);
            for (final SimplePath pathForFrequency : pathsForFrequency) {
                pathCounts.put(pathForFrequency, frequency);
            }
        }
    } else {
        pathCounts = null;
    }
}