Java Code Examples for java.util.Map.merge()

The following are Jave code examples for showing how to use merge() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: rs-aggregator   File: SyncWorkerTest.java   View Source Code Vote up 7 votes
@Test
public void testMerge() {
  Map<String, UrlItem> map = new HashMap<>();

  UrlItem item1 = new UrlItem("abc");
  UrlItem item2 = new UrlItem("abc");

  RsMd rsmd1 = new RsMd()
    .withDateTime(ZonedDateTime.parse("2000-01-01T00:00:00.000Z").withZoneSameInstant(ZoneOffset.UTC));
  item1.withMetadata(rsmd1);

  RsMd rsmd2 = new RsMd()
    .withDateTime(ZonedDateTime.parse("2000-01-01T00:00:01.000Z").withZoneSameInstant(ZoneOffset.UTC));
  item2.withMetadata(rsmd2);


  map.merge("abc", item1, UrlItem::latest);
  assertThat(map.get("abc"), equalTo(item1));

  map.merge("abc", item2, UrlItem::latest);
  assertThat(map.get("abc"), equalTo(item2));

  map.merge("abc", item1, UrlItem::latest);
  assertThat(map.get("abc"), equalTo(item2));

}
 
Example 2
Project: cci   File: CheckPermutationHashMap.java   View Source Code Vote up 7 votes
@Override
public boolean checkPermutation(final String a, final String b) {
    int l = a.length();

    if (l == b.length()) {
        Map<Character, Integer> charMapA = new HashMap<>();
        Map<Character, Integer> charMapB = new HashMap<>();

        for (int i = 0; i < l; i++) {
            charMapA.merge(a.charAt(i), 1, (x, y) -> x + 1);
            charMapB.merge(b.charAt(i), 1, (x, y) -> x + 1);
        }

        return charMapA.equals(charMapB);
    } else {
        return false;
    }
}
 
Example 3
Project: cci   File: PalindromePermutationHashMap.java   View Source Code Vote up 6 votes
@Override
public boolean isPalindromePermutation(final String input) {
    Map<Character, Integer> charCountMap = new HashMap<>();

    for (Character c : input.toCharArray()) {
        charCountMap.merge(c, 1, (a, b) -> a + 1);
    }

    boolean oddFound = false;
    for (Map.Entry<Character, Integer> e : charCountMap.entrySet()) {
        if (charCountMap.get(e.getKey()) % 2 != 0) {
            if (oddFound) {
                return false;
            }

            oddFound = true;
        }
    }

    return true;
}
 
Example 4
Project: monarch   File: DistributedSystemBridge.java   View Source Code Vote up 6 votes
public Map<String, Boolean> viewRemoteClusterStatus() {
  if (mapOfGatewaySenders.values().size() > 0) {
    Map<String, Boolean> senderMap = new HashMap<String, Boolean>();
    Iterator<GatewaySenderMXBean> it = mapOfGatewaySenders.values().iterator();
    while (it.hasNext()) {
      GatewaySenderMXBean bean = it.next();
      Integer dsId = bean.getRemoteDSId();
      if (dsId != null) {
        senderMap.merge(dsId.toString(), bean.isRunning(), Boolean::logicalAnd);
      }
    }

    return senderMap;
  }

  return Collections.emptyMap();
}
 
Example 5
Project: tikv-client-lib-java   File: RegionUtils.java   View Source Code Vote up 6 votes
static public Map<String, Integer>
getRegionDistribution(TiSession session, String databaseName, String tableName) {
  requireNonNull(session, "session is null");
  requireNonNull(databaseName, "databaseName is null");
  requireNonNull(tableName, "tableName is null");
  TiTableInfo table = session.getCatalog().getTable(databaseName, tableName);
  requireNonNull(table, String.format("Table not found %s.%s", databaseName, tableName));
  ScanBuilder builder = new ScanBuilder();
  ScanPlan scanPlan = builder.buildScan(ImmutableList.of(), table);
  List<RegionTask> tasks = RangeSplitter
      .newSplitter(session.getRegionManager())
      .splitRangeByRegion(scanPlan.getKeyRanges());
  Map<String, Integer> regionMap = new HashMap<>();
  for (RegionTask task : tasks) {
    regionMap.merge(task.getHost() + "_" + task.getStore().getId(), 1, Integer::sum);
  }
  return regionMap;
}
 
Example 6
Project: hashsdn-controller   File: CloseTrackedRegistry.java   View Source Code Vote up 6 votes
/**
 * Creates and returns a "report" of (currently) tracked but not (yet) closed
 * instances.
 *
 * @return Set of CloseTrackedRegistryReportEntry, of which each the stack trace
 *         element identifies a unique allocation context (or an empty List if
 *         debugContextEnabled is false), and value is the number of open
 *         instances created at that place in the code.
 */
public Set<CloseTrackedRegistryReportEntry<T>> getAllUnique() {
    Map<List<StackTraceElement>, Long> map = new HashMap<>();
    Set<CloseTracked<T>> copyOfTracked = new HashSet<>(tracked);
    for (CloseTracked<T> closeTracked : copyOfTracked) {
        final StackTraceElement[] stackTraceArray = closeTracked.getAllocationContextStackTrace();
        List<StackTraceElement> stackTraceElements =
                stackTraceArray != null ? Arrays.asList(stackTraceArray) : Collections.emptyList();
        map.merge(stackTraceElements, 1L, (oldValue, value) -> oldValue + 1);
    }

    Set<CloseTrackedRegistryReportEntry<T>> report = new HashSet<>();
    map.forEach((stackTraceElements, number) -> {
        copyOfTracked.stream().filter(closeTracked -> {
            StackTraceElement[] closeTrackedStackTraceArray = closeTracked.getAllocationContextStackTrace();
            List<StackTraceElement> closeTrackedStackTraceElements =
                    closeTrackedStackTraceArray != null ? asList(closeTrackedStackTraceArray) : emptyList();
            return closeTrackedStackTraceElements.equals(stackTraceElements);
        }).findAny().ifPresent(exampleCloseTracked -> {
            report.add(new CloseTrackedRegistryReportEntry<>(exampleCloseTracked, number, stackTraceElements));
        });
    });
    return report;
}
 
Example 7
Project: cruise-control   File: CruiseControlMetricsProcessor.java   View Source Code Vote up 5 votes
/**
 * A helper function to get the number of leader partitions for each topic on each broker. It is useful to
 * derive the partition level IO from the topic level IO on a broker.
 * TODO: create open source KIP to provide per partition IO metrics.
 */
private Map<Integer, Map<String, Integer>> leaderDistributionStats(Cluster cluster) {
  Map<Integer, Map<String, Integer>> stats = new HashMap<>();
  for (Node node : cluster.nodes()) {
    Map<String, Integer> numLeadersByTopic = new HashMap<>();
    stats.put(node.id(), numLeadersByTopic);
    for (PartitionInfo partitionInfo : cluster.partitionsForNode(node.id())) {
      numLeadersByTopic.merge(partitionInfo.topic(), 1, (v0, v1) -> v0 + v1);
    }
  }
  return stats;
}
 
Example 8
Project: stroom-stats   File: StatisticsFlatMappingServiceIT.java   View Source Code Vote up 5 votes
/**
 * Recursive function to walk up each iteration of time intervals until the biggest calculating the
 * expected count for each interval along the way
 */
private void addExpectedCount(int expectedCount, EventStoreTimeIntervalEnum currInterval, Map<EventStoreTimeIntervalEnum, Integer> countsMap) {
    countsMap.merge(currInterval, expectedCount, (v1, v2) -> v1 + v2);

    EventStoreTimeIntervalEnum.getNextBiggest(currInterval)
            .ifPresent(nextInterval -> addExpectedCount(expectedCount, nextInterval, countsMap));
}
 
Example 9
Project: happy-news   File: PositivityAnalyzer.java   View Source Code Vote up 5 votes
/**
 * Gets the unique words per text and their frequency.
 *
 * @param inputText text to be filtered on words
 * @return map of the unique words and their respective counts
 */
private Map<String, Integer> getUniqueWords(String inputText) {
    String[] words = inputText.split("[,.:;\\s\\n]");
    Map<String, Integer> uniqueWords = new HashMap<>();
    for (String word : words) {
        uniqueWords.merge(word, 1, (integer, integer2) -> integer + integer2);
    }
    uniqueWords.remove("");
    return uniqueWords;
}
 
Example 10
Project: oneops   File: CiStateProcessor.java   View Source Code Vote up 5 votes
public void updateState4MonitorRemoval(long manifestId, String source) {
    List<Long> ciIds = tsDao.getManifestCiIds(manifestId, 3, 10000, true);
    Map<Long, List<CiOpenEvent>> openEvents = opsEventDao.getCiOpenEvents(ciIds);
    Map<String, Long> countersDeltaMap = new HashMap<String, Long>();
    for (Map.Entry<Long, List<CiOpenEvent>> entry : openEvents.entrySet()) {
        long ciId = entry.getKey();
        List<CiOpenEvent> bomOpenEvents = entry.getValue();
        Map<String, List<CiOpenEvent>> eventGroupMap = bomOpenEvents.stream().collect(
        		Collectors.groupingBy(ciOpenEvent -> ciOpenEvent.getName().startsWith(source + ":") ? "expiredOpenEvents" : "validOpenEvents"));
        List<CiOpenEvent> expiredOpenEvents = eventGroupMap.get("expiredOpenEvents");
        
        if (expiredOpenEvents != null && !expiredOpenEvents.isEmpty()) {
            String oldState = coProcessor.getState(bomOpenEvents);
        	expiredOpenEvents.stream().forEach(ciOpenEvent -> opsEventDao.removeOpenEventForCi(ciId, ciOpenEvent.getName()));
        	List<CiOpenEvent> validOpenEvents = eventGroupMap.get("validOpenEvents");
        	if (validOpenEvents == null) 
        		validOpenEvents = Collections.emptyList();
            String newState = coProcessor.getState(validOpenEvents);
            if (!oldState.equals(newState)) {
            	countersDeltaMap.merge(oldState, -1L, Long::sum);
            	countersDeltaMap.merge(newState, 1L, Long::sum);
            }
        }
    }
    if (logger.isDebugEnabled()) {
    	logger.debug("state counter delta for monitor removal for manifest " + manifestId + "-" + source + " : " + countersDeltaMap);
    }
    if (!openEvents.isEmpty()) {
        coProcessor.resetManifestStateCounters(manifestId, ciIds, countersDeltaMap);
    }
}
 
Example 11
Project: jdk8u-jdk   File: Defaults.java   View Source Code Vote up 5 votes
@Test(dataProvider = "MergeCases")
private void testMerge(String description, Map<IntegerEnum, String> map, Merging.Value oldValue, Merging.Value newValue, Merging.Merger merger, Merging.Value put, Merging.Value result) {
        // add and check initial conditions.
        switch(oldValue) {
            case ABSENT :
                map.remove(EXTRA_KEY);
                assertFalse(map.containsKey(EXTRA_KEY), "key not absent");
                break;
            case NULL :
                map.put(EXTRA_KEY, null);
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertNull(map.get(EXTRA_KEY), "wrong value");
                break;
            case OLDVALUE :
                map.put(EXTRA_KEY, VALUES[1]);
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertSame(map.get(EXTRA_KEY), VALUES[1], "wrong value");
                break;
            default:
                fail("unexpected old value");
        }

        String returned = map.merge(EXTRA_KEY,
            newValue == Merging.Value.NULL ? (String) null : VALUES[2],
            merger
            );

        // check result

        switch(result) {
            case NULL :
                assertNull(returned, "wrong value");
                break;
            case NEWVALUE :
                assertSame(returned, VALUES[2], "wrong value");
                break;
            case RESULT :
                assertSame(returned, VALUES[3], "wrong value");
                break;
            default:
                fail("unexpected new value");
        }

        // check map
        switch(put) {
            case ABSENT :
                assertFalse(map.containsKey(EXTRA_KEY), "key not absent");
                break;
            case NULL :
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertNull(map.get(EXTRA_KEY), "wrong value");
                break;
            case NEWVALUE :
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertSame(map.get(EXTRA_KEY), VALUES[2], "wrong value");
                break;
            case RESULT :
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertSame(map.get(EXTRA_KEY), VALUES[3], "wrong value");
                break;
            default:
                fail("unexpected new value");
        }
}
 
Example 12
Project: rawhttp   File: RawHttpHeaders.java   View Source Code Vote up 5 votes
public void forEach(BiConsumer<String, String> consumer) {
    Map<String, Integer> currentIndex = new HashMap<>(valuesByCapitalizedName.size());
    for (String name : headerNames) {
        String key = name.toUpperCase();
        currentIndex.merge(key, 0, (a, b) -> a + 1);
        String value = valuesByCapitalizedName.get(key).get(currentIndex.get(key));
        consumer.accept(name, value);
    }
}
 
Example 13
Project: openjdk-jdk10   File: InPlaceOpsCollisions.java   View Source Code Vote up 5 votes
@Test(dataProvider = "hashMapsWithObjects")
void testMergeNonNull(String desc, Supplier<Map<IntKey, IntKey>> ms, IntKey val) {
    // remove a third of the keys
    // call merge() for all keys[]
    // all keys should be present: removed keys now -> EXTRA, other keys -> k-1
    Map<IntKey, IntKey> map = ms.get();
    IntKey[] keys = map.keySet().stream().sorted().toArray(IntKey[]::new);

    // Map to preceding key
    BiFunction<IntKey, IntKey, IntKey> mappingFunction
            = (k, v) -> keys[k.getValue() - 1];
    removeThirdKeys(map, keys);
    for (int i = 1; i < keys.length; i++) {
        IntKey retVal = map.merge(keys[i], val, mappingFunction);
        if (i % 3 != 2) { // key present, should be mapped to k-1
            assertEquals(retVal, keys[i - 1],
                    String.format("compute: retVal(%s[%d])", desc, i));
            assertEquals(keys[i - 1], map.get(keys[i]),
                    String.format("compute: get(%s[%d])", desc, i));
        } else { // odd: was removed, should be replaced with EXTRA
            assertEquals(retVal, val,
                    String.format("compute: retVal(%s[%d])", desc, i));
            assertEquals(val, map.get(keys[i]),
                    String.format("compute: get(%s[%d])", desc, i));
        }
        assertTrue(map.containsKey(keys[i]),
                String.format("compute: containsKey(%s[%d])", desc, i));
    }

    assertEquals(map.size(), keys.length,
            String.format("map expected size#1 m%d != k%d", map.size(), keys.length));
    assertTrue(map.containsValue(val),
            String.format("compute: containsValue(%s[%s])", desc, val));
    assertFalse(map.containsValue(null),
            String.format("compute: !containsValue(%s,[null])", desc));
}
 
Example 14
Project: openjdk-jdk10   File: InPlaceOpsCollisions.java   View Source Code Vote up 5 votes
@Test(dataProvider = "mapsWithObjectsAndStrings")
void testMergeNull(String desc, Supplier<Map<Object, Object>> ms, Object val) {
    // remove a third of the keys
    // call merge() for all keys[]
    // result: removed keys -> EXTRA, other keys absent

    Map<Object, Object> map = ms.get();
    Object[] keys = map.keySet().toArray();
    BiFunction<Object, Object, Object> mappingFunction = (k, v) -> null;
    int expectedSize = 0;
    removeThirdKeys(map, keys);
    for (int i = 0; i < keys.length; i++) {
        Object retVal = map.merge(keys[i], val, mappingFunction);
        if (i % 3 != 2) { // key present, func returned null, should be absent from map
            assertNull(retVal,
                    String.format("compute: retVal(%s[%d])", desc, i));
            assertNull(map.get(keys[i]),
                    String.format("compute: get(%s[%d])", desc, i));
            assertFalse(map.containsKey(keys[i]),
                    String.format("compute: containsKey(%s[%d])", desc, i));
        } else { // odd: was removed, should now be mapped to EXTRA
            assertEquals(retVal, val,
                    String.format("compute: retVal(%s[%d])", desc, i));
            assertEquals(val, map.get(keys[i]),
                    String.format("compute: get(%s[%d])", desc, i));
            assertTrue(map.containsKey(keys[i]),
                    String.format("compute: containsKey(%s[%d])", desc, i));
            expectedSize++;
        }
        assertFalse(map.containsValue(keys[i]),
                String.format("compute: containsValue(%s[%s])", desc, i));
    }
    assertTrue(map.containsValue(val),
            String.format("compute: containsValue(%s[%s])", desc, val));
    assertEquals(map.size(), expectedSize,
            String.format("map expected size#1 m%d != k%d", map.size(), expectedSize));
}
 
Example 15
Project: clearwsd   File: VerbNetExperiment.java   View Source Code Vote up 5 votes
private static List<NlpFocus<DepNode, DepTree>> filterMinCount(int minCount,
                                                               List<NlpFocus<DepNode, DepTree>> data) {
    Map<String, Integer> counts = new HashMap<>();
    for (NlpFocus<DepNode, DepTree> instance : data) {
        String lemma = instance.focus().feature(FeatureType.Predicate);
        counts.merge(lemma, 1, (prev, one) -> prev + one);
    }
    return data.stream()
            .filter(instance -> {
                String predicate = instance.focus().feature(FeatureType.Predicate);
                return counts.get(predicate) >= minCount;
            })
            .collect(Collectors.toList());
}
 
Example 16
Project: openjdk-jdk10   File: ResponseHeaders.java   View Source Code Vote up 4 votes
private Map<String, List<String>> parse(InputStreamWrapper input)
     throws IOException
{
    // The bulk of work is done by this time-proven class
    MessageHeader h = new MessageHeader();
    h.parseHeader(input);

    // When there are no headers (and therefore no body), the status line
    // will be followed by an empty CRLF line.
    // In that case MessageHeader.parseHeader() will consume the first
    // CR character and stop there. In this case we must consume the
    // remaining LF.
    if (input.consumed == 1 && CR == (char) input.lastRead) {
        // MessageHeader will not consume LF if the first character it
        // finds is CR. This only happens if there are no headers, and
        // only one byte will be consumed from the buffer. In this case
        // the next byte MUST be LF
        if (input.read() != LF) {
            throw new IOException("Unexpected byte sequence when no headers: "
                 + ((int)CR) + " " + input.lastRead
                 + "(" + ((int)CR) + " " + ((int)LF) + " expected)");
        }
    }

    Map<String, List<String>> rawHeaders = h.getHeaders();

    // Now some additional post-processing to adapt the results received
    // from MessageHeader to what is needed here
    Map<String, List<String>> cookedHeaders = new HashMap<>();
    for (Map.Entry<String, List<String>> e : rawHeaders.entrySet()) {
        String key = e.getKey();
        if (key == null) {
            throw new ProtocolException("Bad header-field");
        }
        if (!isValidName(key)) {
            throw new ProtocolException(format(
                    "Bad header-name: '%s'", key));
        }
        List<String> newValues = e.getValue();
        for (String v : newValues) {
            if (!isValidValue(v)) {
                throw new ProtocolException(format(
                        "Bad header-value for header-name: '%s'", key));
            }
        }
        String k = key.toLowerCase(Locale.US);
        cookedHeaders.merge(k, newValues,
                (v1, v2) -> {
                    ArrayList<String> newV = new ArrayList<>();
                    if (v1 != null) {
                        newV.addAll(v1);
                    }
                    newV.addAll(v2);
                    return newV;
                });
    }
    return cookedHeaders;
}
 
Example 17
Project: openjdk-jdk10   File: Defaults.java   View Source Code Vote up 4 votes
@Test(dataProvider = "MergeCases")
private void testMerge(String description, Map<IntegerEnum, String> map, Merging.Value oldValue, Merging.Value newValue, Merging.Merger merger, Merging.Value put, Merging.Value result) {
        // add and check initial conditions.
        switch (oldValue) {
            case ABSENT :
                map.remove(EXTRA_KEY);
                assertFalse(map.containsKey(EXTRA_KEY), "key not absent");
                break;
            case NULL :
                map.put(EXTRA_KEY, null);
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertNull(map.get(EXTRA_KEY), "wrong value");
                break;
            case OLDVALUE :
                map.put(EXTRA_KEY, VALUES[1]);
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertSame(map.get(EXTRA_KEY), VALUES[1], "wrong value");
                break;
            default:
                fail("unexpected old value");
        }

        String returned = map.merge(EXTRA_KEY,
            newValue == Merging.Value.NULL ? (String) null : VALUES[2],
            merger
            );

        // check result

        switch (result) {
            case NULL :
                assertNull(returned, "wrong value");
                break;
            case NEWVALUE :
                assertSame(returned, VALUES[2], "wrong value");
                break;
            case RESULT :
                assertSame(returned, VALUES[3], "wrong value");
                break;
            default:
                fail("unexpected new value");
        }

        // check map
        switch (put) {
            case ABSENT :
                assertFalse(map.containsKey(EXTRA_KEY), "key not absent");
                break;
            case NULL :
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertNull(map.get(EXTRA_KEY), "wrong value");
                break;
            case NEWVALUE :
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertSame(map.get(EXTRA_KEY), VALUES[2], "wrong value");
                break;
            case RESULT :
                assertTrue(map.containsKey(EXTRA_KEY), "key absent");
                assertSame(map.get(EXTRA_KEY), VALUES[3], "wrong value");
                break;
            default:
                fail("unexpected new value");
        }
}
 
Example 18
Project: clearwsd   File: CountingSenseInventory.java   View Source Code Vote up 4 votes
@Override
public void addSense(String lemma, String sense) {
    Map<String, Integer> current = inventoryMap.computeIfAbsent(lemma, k -> new HashMap<>());
    current.merge(sense, 1, (old, one) -> old + one);
}