本文整理匯總了Java中java.util.Map.merge方法的典型用法代碼示例。如果您正苦於以下問題:Java Map.merge方法的具體用法?Java Map.merge怎麽用?Java Map.merge使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.Map
的用法示例。
在下文中一共展示了Map.merge方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: testMerge
import java.util.Map; //導入方法依賴的package包/類
@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));
}
示例2: checkPermutation
import java.util.Map; //導入方法依賴的package包/類
@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;
}
}
示例3: isPalindromePermutation
import java.util.Map; //導入方法依賴的package包/類
@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;
}
示例4: viewRemoteClusterStatus
import java.util.Map; //導入方法依賴的package包/類
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();
}
示例5: getRegionDistribution
import java.util.Map; //導入方法依賴的package包/類
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;
}
示例6: getAllUnique
import java.util.Map; //導入方法依賴的package包/類
/**
* 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;
}
示例7: leaderDistributionStats
import java.util.Map; //導入方法依賴的package包/類
/**
* 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;
}
示例8: addExpectedCount
import java.util.Map; //導入方法依賴的package包/類
/**
* 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));
}
示例9: getUniqueWords
import java.util.Map; //導入方法依賴的package包/類
/**
* 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;
}
示例10: updateState4MonitorRemoval
import java.util.Map; //導入方法依賴的package包/類
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);
}
}
示例11: testMerge
import java.util.Map; //導入方法依賴的package包/類
@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");
}
}
示例12: forEach
import java.util.Map; //導入方法依賴的package包/類
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);
}
}
示例13: testMergeNonNull
import java.util.Map; //導入方法依賴的package包/類
@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));
}
示例14: testMergeNull
import java.util.Map; //導入方法依賴的package包/類
@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));
}
示例15: filterMinCount
import java.util.Map; //導入方法依賴的package包/類
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());
}