Example usage for java.util Map compute

List of usage examples for java.util Map compute

Introduction

In this page you can find the example usage for java.util Map compute.

Prototype

default V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) 

Source Link

Document

Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).

Usage

From source file:org.codice.ddf.catalog.ui.query.monitor.impl.WorkspaceQueryService.java

private Map<String, List<QueryMetacardImpl>> groupBySource(List<QueryMetacardImpl> queryMetacards) {
    final Map<String, List<QueryMetacardImpl>> groupedBySource = new HashMap<>();
    for (QueryMetacardImpl queryMetacard : queryMetacards) {

        List<String> sources = queryMetacard.getSources();

        if (!sources.isEmpty()) {
            sources.forEach(sourceId -> groupedBySource.compute(sourceId, addToList(queryMetacard)));
        } else {//from  w  w  w. j av a  2  s.c  om
            groupedBySource.compute(UNKNOWN_SOURCE, addToList(queryMetacard));
        }
    }
    return groupedBySource;
}

From source file:org.codice.ddf.catalog.ui.query.monitor.impl.WorkspaceQueryServiceImpl.java

private Map<String, List<QueryMetacardImpl>> groupBySource(List<QueryMetacardImpl> queryMetacards) {
    final Map<String, List<QueryMetacardImpl>> groupedBySource = new HashMap<>();
    for (QueryMetacardImpl queryMetacard : queryMetacards) {
        List<String> sources = queryMetacard.getSources();
        if (!sources.isEmpty()) {
            sources.forEach(sourceId -> groupedBySource.compute(sourceId, addToList(queryMetacard)));
        } else {//from   w w w  . j  ava2  s  . c  o  m
            groupedBySource.compute(UNKNOWN_SOURCE, addToList(queryMetacard));
        }
    }
    return groupedBySource;
}

From source file:org.onosproject.openstacknetworking.util.OpenstackNetworkingUtilTest.java

/**
 * Tests the getGwByComputeDevId method.
 *///w w w  . j a v a  2  s  .  c o  m
@Test
public void testGetGwByComputeDevId() {
    Set<OpenstackNode> gws = Sets.newConcurrentHashSet();
    gws.add(genGateway(1));
    gws.add(genGateway(2));
    gws.add(genGateway(3));

    Set<OpenstackNode> cloneOfGws = ImmutableSet.copyOf(gws);

    Map<String, Integer> gwCountMap = Maps.newConcurrentMap();
    int numOfDev = 99;

    for (int i = 1; i < 1 + numOfDev; i++) {
        OpenstackNode gw = getGwByComputeDevId(gws, genDeviceId(i));

        if (gwCountMap.get(gw.hostname()) == null) {
            gwCountMap.put(gw.hostname(), 1);
        } else {
            gwCountMap.compute(gw.hostname(), (k, v) -> v + 1);
        }

        new EqualsTester().addEqualityGroup(getGwByComputeDevId(gws, genDeviceId(i)),
                getGwByComputeDevId(cloneOfGws, genDeviceId(i))).testEquals();
    }

    int sum = gwCountMap.values().stream().mapToInt(Integer::intValue).sum();
    assertEquals(numOfDev, sum);
}

From source file:org.sonar.server.qualityprofile.DefinedQProfileRepositoryImpl.java

/**
 * Creates {@link DefinedQProfile.Builder} for each unique quality profile name for a given language.
 * Builders will have the following properties populated:
 * <ul>/*from  w  ww.java 2s .c o  m*/
 *   <li>{@link DefinedQProfile.Builder#language language}: key of the method's parameter</li>
 *   <li>{@link DefinedQProfile.Builder#name name}: {@link RulesProfile#getName()}</li>
 *   <li>{@link DefinedQProfile.Builder#declaredDefault declaredDefault}: {@code true} if at least one RulesProfile
 *       with a given name has {@link RulesProfile#getDefaultProfile()} is {@code true}</li>
 *   <li>{@link DefinedQProfile.Builder#activeRules activeRules}: the concatenate of the active rules of all
 *       RulesProfile with a given name</li>
 * </ul>
 */
private static List<DefinedQProfile.Builder> toQualityProfileBuilders(
        Map.Entry<String, List<RulesProfile>> rulesProfilesByLanguage) {
    String language = rulesProfilesByLanguage.getKey();
    // use a LinkedHashMap to keep order of insertion of RulesProfiles
    Map<String, DefinedQProfile.Builder> qualityProfileBuildersByName = new LinkedHashMap<>();
    for (RulesProfile rulesProfile : rulesProfilesByLanguage.getValue()) {
        qualityProfileBuildersByName.compute(rulesProfile.getName(),
                (name, existingBuilder) -> updateOrCreateBuilder(language, existingBuilder, rulesProfile));
    }
    return ImmutableList.copyOf(qualityProfileBuildersByName.values());
}

From source file:org.springframework.kafka.core.KafkaAdmin.java

private void addTopicsIfNeeded(AdminClient adminClient, Collection<NewTopic> topics) {
    if (topics.size() > 0) {
        Map<String, NewTopic> topicNameToTopic = new HashMap<>();
        topics.forEach(t -> topicNameToTopic.compute(t.name(), (k, v) -> v = t));
        DescribeTopicsResult topicInfo = adminClient
                .describeTopics(topics.stream().map(NewTopic::name).collect(Collectors.toList()));
        List<NewTopic> topicsToAdd = new ArrayList<>();
        Map<String, NewPartitions> topicsToModify = checkPartitions(topicNameToTopic, topicInfo, topicsToAdd);
        if (topicsToAdd.size() > 0) {
            addTopics(adminClient, topicsToAdd);
        }/*from   w w  w  .  java  2  s. c  om*/
        if (topicsToModify.size() > 0) {
            modifyTopics(adminClient, topicsToModify);
        }
    }
}

From source file:svnserver.repository.git.prop.GitAttributes.java

@Override
public void apply(@NotNull Map<String, String> props) {
    if (eolDir.rules.length > 0) {
        final Map<String, String> autoprops = new LinkedHashMap<>();
        for (Rule rule : eolDir.rules) {
            autoprops.compute(rule.mask,
                    (key, value) -> (value == null ? "" : value + "; ") + rule.prop + "=" + rule.value);
        }/*w w  w  .  j  a v  a2s.  c om*/
        final StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : autoprops.entrySet()) {
            sb.append(entry.getKey()).append(" = ").append(entry.getValue()).append('\n');
        }
        props.put(SVNProperty.INHERITABLE_AUTO_PROPS, sb.toString());
    }
}

From source file:svnserver.repository.git.prop.GitIgnore.java

@Override
public void apply(@NotNull Map<String, String> props) {
    if (global.length > 0) {
        props.compute(SVNProperty.INHERITABLE_IGNORES, (key, value) -> addIgnore(value, global));
    }/* w  w w . java2  s. c o m*/
    if (local.length > 0) {
        props.compute(SVNProperty.IGNORE, (key, value) -> addIgnore(value, local));
    }
}

From source file:systems.composable.dropwizard.cassandra.cli.CommandInfo.java

@Override
void run(Namespace namespace, CassandraMigration cassandraMigration, Session session) throws Exception {
    final MigrationInfo[] migrationInfos = cassandraMigration.info(session).all();
    if (migrationInfos.length == 0)
        throw new IllegalStateException("No migration scripts found");

    final Map<String, Integer> widths = new HashMap<>();
    final List<Map<String, String>> rows = new LinkedList<>();

    INFOS.forEach(col -> widths.compute(col, (k, v) -> k.length()));
    Arrays.stream(migrationInfos).forEach(migrationInfo -> {
        final Map<String, String> row = new HashMap<>();
        INFOS.forEach(col -> {/*w ww .  jav  a2s  .com*/
            final String cell;
            switch (col) {
            case INFO_TYPE:
                cell = migrationInfo.getType().toString();
                break;
            case INFO_STATE:
                cell = migrationInfo.getState().getDisplayName();
                break;
            case INFO_VERSION:
                cell = migrationInfo.getVersion().toString();
                break;
            case INFO_DESC:
                cell = migrationInfo.getDescription();
                break;
            case INFO_SCRIPT:
                cell = migrationInfo.getScript();
                break;
            case INFO_CHKSUM:
                cell = String.valueOf(migrationInfo.getChecksum());
                break;
            case INFO_INST_ON:
                final Date d = migrationInfo.getInstalledOn();
                cell = d != null ? d.toInstant().toString() : "";
                break;
            case INFO_EXEC_MS:
                final Integer ms = migrationInfo.getExecutionTime();
                cell = ms != null ? Duration.of(ms, ChronoUnit.MILLIS).toString() : "";
                break;
            default:
                cell = "";
            }
            row.put(col, cell);
            widths.compute(col, (k, v) -> Math.max(cell.length(), v));
        });
        rows.add(row);
    });

    final String separator = "+"
            + INFOS.stream().map(col -> repeat('-', widths.get(col) + 2)).collect(Collectors.joining("+")) + "+"
            + System.lineSeparator();

    final StringBuilder sb = new StringBuilder().append(separator).append('|')
            .append(INFOS.stream().map(col -> " " + center(col, widths.get(col)) + " ")
                    .collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()).append(separator);
    rows.forEach(row -> sb.append('|').append(INFOS.stream()
            .map(col -> " " + leftPad(row.get(col), widths.get(col)) + " ").collect(Collectors.joining("|")))
            .append('|').append(System.lineSeparator()));
    sb.append(separator);
    System.out.print(sb.toString());
}