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

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

Introduction

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

Prototype

public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Creates an index ImmutableListMultimap that contains the results of applying a specified function to each item in an Iterator of values.

Usage

From source file:org.example.guava.ListGroupExample.java

public static void main(String[] args) {
    List list = new ArrayList();
    list.add(new Entry(20, "xiaosan1"));
    list.add(new Entry(18, "xiaosan2"));
    list.add(new Entry(18, "xiaosan3"));
    list.add(new Entry(20, "xiaosan4"));
    list.add(new Entry(18, "xiaosan5"));
    list.add(new Entry(20, "xiaosan6"));

    /*/*  www  . j  a v  a 2  s .  c  o  m*/
    :??
     */
    Map<Integer, Entry> map = Multimaps.index(list, new Function<Entry, Integer>() {
        @Override
        public Integer apply(Entry input) {
            return input.getAge();
        }

    }).asMap();

    /*
    output:
    {20=[Entry{age=20,name=xiaosan1}, Entry{age=20,name=xiaosan4}, Entry{age=20,name=xiaosan6}], 18=[Entry{age=18,name=xiaosan2}, Entry{age=18,name=xiaosan3}, Entry{age=18,name=xiaosan5}]}
     */
    System.out.println(map);
}

From source file:org.obeonetwork.dsl.uml2.design.tests.common.EObjects.java

public static ImmutableListMultimap<EClass, EObject> perType(Iterable<EObject> objects) {
    return Multimaps.index(objects, EObjects.toEclass);
}

From source file:net.oneandone.maven.rules.common.RuleHelper.java

public static ImmutableListMultimap<String, Dependency> getManagedDependenciesAsMap(MavenProject project) {
    if (project.getDependencyManagement() != null) {
        return Multimaps.index(project.getDependencyManagement().getDependencies(),
                new Function<Dependency, String>() {
                    public String apply(Dependency from) {
                        if (from != null) {
                            return from.getGroupId() + ":" + from.getArtifactId();
                        }/* w ww .j  av a 2s  .  c o m*/

                        return null;
                    }
                });

    }
    return ImmutableListMultimap.of();
}

From source file:springfox.documentation.spring.web.plugins.DuplicateGroupsDetector.java

public static void ensureNoDuplicateGroups(List<DocumentationPlugin> allPlugins) throws IllegalStateException {
    Multimap<String, DocumentationPlugin> plugins = Multimaps.index(allPlugins, byGroupName());
    Iterable<String> duplicateGroups = from(plugins.asMap().entrySet()).filter(duplicates())
            .transform(toGroupNames());//from   w  w w  .j  av  a 2s . c  om
    if (Iterables.size(duplicateGroups) > 0) {
        throw new IllegalStateException(String.format(
                "Multiple Dockets with the same group name are not supported. "
                        + "The following duplicate groups were discovered. %s",
                Joiner.on(',').join(duplicateGroups)));
    }
}

From source file:eu.itesla_project.commons.tools.Main.java

private static void printUsage() {
    StringBuilder usage = new StringBuilder();
    usage.append("usage: " + TOOL_NAME + " COMMAND [ARGS]\n\nAvailable commands are:\n\n");

    List<Tool> allTools = Lists.newArrayList(ServiceLoader.load(Tool.class)).stream()
            .filter(t -> !t.getCommand().isHidden()).collect(Collectors.toList());

    // group commands by theme
    Multimap<String, Tool> toolsByTheme = Multimaps.index(allTools, new Function<Tool, String>() {
        @Override/*from www.  ja va  2s . com*/
        public String apply(Tool tool) {
            return tool.getCommand().getTheme();
        }
    });

    for (Map.Entry<String, Collection<Tool>> entry : toolsByTheme.asMap().entrySet()) {
        String theme = entry.getKey();
        List<Tool> tools = new ArrayList<>(entry.getValue());
        Collections.sort(tools, new Comparator<Tool>() {
            @Override
            public int compare(Tool t1, Tool t2) {
                return t1.getCommand().getName().compareTo(t2.getCommand().getName());
            }
        });
        usage.append(theme != null ? theme : "Others").append(":\n");
        for (Tool tool : tools) {
            usage.append(String.format("   %-40s %s", tool.getCommand().getName(),
                    tool.getCommand().getDescription())).append("\n");
        }
        usage.append("\n");
    }

    System.err.print(usage);
    System.exit(1);
}

From source file:com.google.caliper.model.Measurement.java

public static ImmutableListMultimap<String, Measurement> indexByDescription(
        Iterable<Measurement> measurements) {
    return Multimaps.index(measurements, new Function<Measurement, String>() {
        @Override/*from w w w  .j  a va2s.  c  om*/
        public String apply(Measurement input) {
            return input.description;
        }
    });
}

From source file:io.crate.frameworks.mesos.config.Resources.java

@SuppressWarnings("RedundantIfStatement")
public static boolean matches(List<Protos.Resource> offeredResources, Configuration configuration) {
    ImmutableListMultimap<String, Protos.Resource> resourceMap = Multimaps.index(offeredResources,
            RESOURCE_NAME);/*from   w ww.  j  a va 2s  . co m*/

    Protos.Resource cpus1 = getOnlyElement(resourceMap.get("cpus"));
    if (cpus1.getScalar().getValue() < configuration.resCpus) {
        return false;
    }

    Protos.Resource mem = getOnlyElement(resourceMap.get("mem"));

    if (mem.getScalar().getValue() < configuration.resMemory) {
        return false;
    }

    ImmutableList<Protos.Resource> ports = resourceMap.get("ports");
    if (!isPortInRange(configuration.httpPort, ports)) {
        return false;
    }
    if (!isPortInRange(configuration.transportPort, ports)) {
        return false;
    }

    return true;
}

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

/** Indexes objects by their contribution type. */
static <T extends HasContributionType> ImmutableListMultimap<ContributionType, T> indexByContributionType(
        Iterable<T> haveContributionTypes) {
    return Multimaps.index(haveContributionTypes, new Function<HasContributionType, ContributionType>() {
        @Override//from w w  w. j av  a2 s .  c o m
        public ContributionType apply(HasContributionType hasContributionType) {
            return hasContributionType.contributionType();
        }
    });
}

From source file:eu.itesla_project.modules.rules.SecurityRuleUtil.java

public static Map<String, Map<SecurityIndexType, SecurityRuleCheckStatus>> checkRules(Network network,
        RulesDbClient rulesDb, String workflowId, RuleAttributeSet attributeSet,
        Set<SecurityIndexType> securityIndexTypes, Set<String> contingencies, double purityThreshold) {
    Map<HistoDbAttributeId, Object> values = IIDM2DB.extractCimValues(network, new IIDM2DB.Config(null, false))
            .getSingleValueMap();//  w  ww .j a v a2  s.  c  o  m

    // check rules
    Map<String, Map<SecurityIndexType, SecurityRuleCheckStatus>> checkStatusPerContingency = new LinkedHashMap<>();

    // get rules from db
    Collection<RuleId> ruleIds = rulesDb.listRules(workflowId, attributeSet).stream()
            .filter(ruleId -> securityIndexTypes.contains(ruleId.getSecurityIndexId().getSecurityIndexType())
                    && (contingencies == null
                            || contingencies.contains(ruleId.getSecurityIndexId().getContingencyId())))
            .collect(Collectors.toList());

    // TODO filter rules that does not apply to the network

    // sort rules per contingency
    Multimap<String, RuleId> ruleIdsPerContingency = Multimaps.index(ruleIds, ruleId -> {
        return ruleId.getSecurityIndexId().getContingencyId();
    });

    for (Map.Entry<String, Collection<RuleId>> entry : ruleIdsPerContingency.asMap().entrySet()) {
        String contingencyId = entry.getKey();

        Map<SecurityIndexType, SecurityRuleCheckStatus> checkStatus = new EnumMap<>(SecurityIndexType.class);
        for (SecurityIndexType securityIndexType : securityIndexTypes) {
            checkStatus.put(securityIndexType, SecurityRuleCheckStatus.NA);
        }

        for (RuleId ruleId : entry.getValue()) {
            List<SecurityRule> rules = rulesDb.getRules(workflowId, attributeSet, contingencyId,
                    ruleId.getSecurityIndexId().getSecurityIndexType());
            if (rules.size() > 0) {
                SecurityRule rule = rules.get(0);
                SecurityRuleExpression securityRuleExpression = rule.toExpression(purityThreshold);
                SecurityRuleCheckReport report = securityRuleExpression.check(values);
                SecurityRuleCheckStatus status;
                if (report.getMissingAttributes().isEmpty()) {
                    status = report.isSafe() ? SecurityRuleCheckStatus.OK : SecurityRuleCheckStatus.NOK;
                } else {
                    status = SecurityRuleCheckStatus.NA;
                }
                checkStatus.put(rule.getId().getSecurityIndexId().getSecurityIndexType(), status);
            }
        }

        checkStatusPerContingency.put(contingencyId, checkStatus);
    }

    return checkStatusPerContingency;
}

From source file:com.github.tomakehurst.wiremock.recording.ScenarioProcessor.java

public void putRepeatedRequestsInScenarios(List<StubMapping> stubMappings) {
    ImmutableListMultimap<RequestPattern, StubMapping> stubsGroupedByRequest = Multimaps.index(stubMappings,
            new Function<StubMapping, RequestPattern>() {
                @Override//from ww  w  .j  a va 2s . com
                public RequestPattern apply(StubMapping mapping) {
                    return mapping.getRequest();
                }
            });

    Map<RequestPattern, Collection<StubMapping>> groupsWithMoreThanOneStub = Maps.filterEntries(
            stubsGroupedByRequest.asMap(), new Predicate<Map.Entry<RequestPattern, Collection<StubMapping>>>() {
                @Override
                public boolean apply(Map.Entry<RequestPattern, Collection<StubMapping>> input) {
                    return input.getValue().size() > 1;
                }
            });

    for (Map.Entry<RequestPattern, Collection<StubMapping>> entry : groupsWithMoreThanOneStub.entrySet()) {
        putStubsInScenario(ImmutableList.copyOf(entry.getValue()));
    }
}