下面列出了java.util.Map#computeIfPresent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test(dataProvider = "caches")
@CacheSpec(population = Population.FULL, expiryTime = Expire.ONE_MINUTE,
mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE },
expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE },
expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE})
public void computeIfPresent_writeTime(Map<Integer, Integer> map, CacheContext context) {
Integer key = context.firstKey();
Integer value = context.absentValue();
map.computeIfPresent(key, (k, v) -> {
context.ticker().advance(5, TimeUnit.MINUTES);
return value;
});
context.cleanUp();
assertThat(map.size(), is(1));
assertThat(map.containsKey(key), is(true));
}
@Test
public void testMapCompute(){
Map<String, String> map = new HashMap<>();
String putValue = "putValue";
String val = map.compute("test", (k, v)-> v==null?putValue:v+putValue);
Assert.assertEquals(putValue, val);
val = map.put("test", "putValue2");
Assert.assertEquals("putValue", val);
val = map.compute("test", (k, v)-> v==null?putValue:v+putValue);
Assert.assertEquals("putValue2"+putValue, val);
val = map.computeIfPresent("test2", (k, v)-> putValue);
Assert.assertTrue(val==null);
val = map.computeIfAbsent("test2", (v)-> putValue);
Assert.assertEquals(putValue, val);
val = map.computeIfPresent("test2", (k, v)-> v+putValue);
Assert.assertEquals(putValue+putValue, val);
}
public Map<String, Object> toMap(boolean includeDefaultValue, boolean addTypeMarker) {
Map<String, Object> eventMap = ProtoConcatenator.concatToMap(timestamp, Arrays.asList(header, body), includeDefaultValue);
if (addTypeMarker) {
eventMap.put("event_type", GarmadonSerialization.getTypeName(type));
}
// Specific normalization for FS_EVENT
if (GarmadonSerialization.TypeMarker.FS_EVENT == type) {
String uri = (String) eventMap.get("uri");
eventMap.computeIfPresent("src_path", (k, v) -> ((String) v).replace(uri, ""));
eventMap.computeIfPresent("dst_path", (k, v) -> ((String) v).replace(uri, ""));
eventMap.computeIfPresent("uri", (k, v) -> UriHelper.getUniformizedUri((String) v));
}
return eventMap;
}
@Test(dataProvider = "caches", expectedExceptions = DeleteException.class)
@CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG,
population = Population.FULL, expiryTime = Expire.ONE_MINUTE,
mustExpireWithAnyOf = { AFTER_ACCESS, AFTER_WRITE, VARIABLE },
expiry = { CacheExpiry.DISABLED, CacheExpiry.CREATE, CacheExpiry.WRITE, CacheExpiry.ACCESS },
expireAfterAccess = {Expire.DISABLED, Expire.ONE_MINUTE},
expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE},
compute = Compute.SYNC, writer = Writer.EXCEPTIONAL,
executorFailure = ExecutorFailure.EXPECTED, removalListener = Listener.REJECTING)
public void computeIfPresent_writerFails(Map<Integer, Integer> map, CacheContext context) {
try {
Integer key = context.firstKey();
context.ticker().advance(1, TimeUnit.HOURS);
map.computeIfPresent(key, (k, v) -> context.absentValue());
} finally {
context.disableRejectingCacheWriter();
context.ticker().advance(-1, TimeUnit.HOURS);
assertThat(map, equalTo(context.original()));
}
}
/**
* Remove all listeners attached to an object.
*
* @param objectClass The class of the object.
* @param objectId The id of the object.
*/
public void removeObjectListeners(Class<?> objectClass, long objectId) {
if (objectClass == null) {
return;
}
synchronized (objectListeners) {
Map<Long, Map<Class<? extends ObjectAttachableListener>,
Map<ObjectAttachableListener, ListenerManagerImpl<? extends ObjectAttachableListener>>>>
objects = objectListeners.get(objectClass);
if (objects == null) {
return;
}
// Remove all listeners
objects.computeIfPresent(objectId, (id, listeners) -> {
listeners.values().stream()
.flatMap(map -> map.values().stream())
.forEach(ListenerManagerImpl::removed);
listeners.clear();
return null;
});
// Cleanup
if (objects.isEmpty()) {
objectListeners.remove(objectClass);
}
}
}
/**
* Applies the given update function to the rule.
*
* @param rule the rule to update
* @param function the update function to apply
* @param term the term in which the change occurred
* @param clock the logical clock
* @param <T> the result type
* @return the update result or {@code null} if the rule was not updated
*/
public <T> T update(FlowRule rule, Function<StoredFlowEntry, T> function, long term, LogicalClock clock) {
Map<StoredFlowEntry, StoredFlowEntry> flowEntries = flowBucket.get(rule.id());
if (flowEntries == null) {
flowEntries = flowBucket.computeIfAbsent(rule.id(), id -> Maps.newConcurrentMap());
}
AtomicReference<T> resultRef = new AtomicReference<>();
flowEntries.computeIfPresent(new DefaultFlowEntry(rule), (k, stored) -> {
if (stored != null) {
T result = function.apply(stored);
if (result != null) {
recordUpdate(term, clock.getTimestamp());
resultRef.set(result);
}
}
return stored;
});
return resultRef.get();
}
/**
* Remove all listeners attached to an object.
*
* @param objectClass The class of the object.
* @param objectId The id of the object.
*/
public void removeObjectListeners(Class<?> objectClass, long objectId) {
if (objectClass == null) {
return;
}
synchronized (objectListeners) {
Map<Long, Map<Class<? extends ObjectAttachableListener>,
Map<ObjectAttachableListener, ListenerManagerImpl<? extends ObjectAttachableListener>>>>
objects = objectListeners.get(objectClass);
if (objects == null) {
return;
}
// Remove all listeners
objects.computeIfPresent(objectId, (id, listeners) -> {
listeners.values().stream()
.flatMap(map -> map.values().stream())
.forEach(ListenerManagerImpl::removed);
listeners.clear();
return null;
});
// Cleanup
if (objects.isEmpty()) {
objectListeners.remove(objectClass);
}
}
}
private AutoScalingConfig withDefaultTrigger(Map<String, Object> triggerProps, AutoScalingConfig autoScalingConfig) {
String triggerName = (String) triggerProps.get("name");
Map<String, AutoScalingConfig.TriggerConfig> configs = autoScalingConfig.getTriggerConfigs();
for (AutoScalingConfig.TriggerConfig cfg : configs.values()) {
if (triggerName.equals(cfg.name)) {
// already has this trigger
return autoScalingConfig;
}
}
// need to add
triggerProps.computeIfPresent("waitFor", (k, v) -> (long) (DEFAULT_AUTO_ADD_REPLICA_WAIT_FOR_SECONDS));
AutoScalingConfig.TriggerConfig config = new AutoScalingConfig.TriggerConfig(triggerName, triggerProps);
autoScalingConfig = autoScalingConfig.withTriggerConfig(config);
// need to add SystemLogListener explicitly here
autoScalingConfig = AutoScalingHandler.withSystemLogListener(autoScalingConfig, triggerName);
return autoScalingConfig;
}
public void addMethodTransformation(String method, String descriptor, AccessTransformation transformation) {
Map<String, AccessTransformation> transformationSet = methodTransformers.get(method);
if (transformationSet != null) {
transformationSet.computeIfPresent(descriptor, (x, existing) -> {
if (!existing.equals(AccessTransformation.NONE) && !transformation.equals(existing)) {
throw new IllegalStateException("FIXME: Conflicting field access transformations: tried to add a transform of " + transformation + " to " + method + " (descriptor: " + descriptor + ") when " + existing + " already exists");
}
return existing;
});
}
methodTransformers.computeIfAbsent(method, n -> new HashMap<>()).put(descriptor, transformation);
}
public void test_CheckedMap_computeIfPresent() {
Map<Integer, Double> map = new HashMap<>();
Map checkedMap = Collections.checkedMap(map, Integer.class, Double.class);
MapDefaultMethodTester.test_computeIfPresent(checkedMap, true /* acceptsNullKey */);
// Without generics to check the typeCheck implementation
Map m = new HashMap();
Map checkedMap2 = Collections.checkedMap(m, Integer.class, String.class);
checkedMap2.put(1, A_STRING);
try {
checkedMap2.computeIfPresent(1, (k, v) -> NOT_A_STRING);
fail();
} catch (ClassCastException expected) {}
}
@CheckNoWriter @CheckNoStats
@CacheSpec(removalListener = { Listener.DEFAULT, Listener.REJECTING })
@Test(dataProvider = "caches", expectedExceptions = NullPointerException.class)
public void computeIfPresent_nullMappingFunction(
Map<Integer, Integer> map, CacheContext context) {
map.computeIfPresent(1, null);
}
/**
* Create a new DistributedConfig object with a suffix applied to the client id. This allows us to
* make the client id unique so JMX metrics work properly.
*/
private static DistributedConfig configWithClientIdSuffix(
Map<String, String> workerProps, String suffix) {
Map<String, String> localProps = new HashMap<>(workerProps);
localProps.computeIfPresent(CommonClientConfigs.CLIENT_ID_CONFIG, (k, v) -> v + suffix);
return new DistributedConfig(localProps);
}
private AtomicBoolean removeInternal(NetworkId networkId, PacketRequest request) {
AtomicBoolean removedLast = new AtomicBoolean(false);
AtomicBoolean changed = new AtomicBoolean(true);
Map<RequestKey, Set<PacketRequest>> requestsForNetwork = getMap(networkId);
requestsForNetwork.computeIfPresent(key(request), (s, existingRequests) -> {
// Reset to false just in case this is a retry due to
// ConcurrentModificationException
removedLast.set(false);
if (existingRequests.contains(request)) {
Set<PacketRequest> newRequests = Sets.newHashSet(existingRequests);
newRequests.remove(request);
if (newRequests.size() > 0) {
return ImmutableSet.copyOf(newRequests);
} else {
removedLast.set(true);
return null;
}
} else {
changed.set(false);
return existingRequests;
}
});
if (changed.get()) {
requests.put(networkId, requestsForNetwork);
}
return removedLast;
}
private static Consumer<byte[], byte[]> newDestinationConsumer(SourceConfig config) {
Map<String, Object> consumerProperties = config.getConsumerProperties();
// The "monitor2" client id suffix is used to keep JMX bean names distinct
consumerProperties.computeIfPresent(
CommonClientConfigs.CLIENT_ID_CONFIG, (k, v) -> v + "monitor2");
consumerProperties.put(
ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getDestinationBootstrapServers());
return new KafkaConsumer<>(consumerProperties);
}
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));
map.computeIfPresent(3, (num, val) -> val + num);
System.out.println(map.get(3)); // val33
map.computeIfPresent(9, (num, val) -> null);
System.out.println(map.containsKey(9)); // false
map.computeIfAbsent(23, num -> "val" + num);
System.out.println(map.containsKey(23)); // true
map.computeIfAbsent(3, num -> "bam");
System.out.println(map.get(3)); // val33
System.out.println(map.getOrDefault(42, "not found")); // not found
map.remove(3, "val3");
System.out.println(map.get(3)); // val33
map.remove(3, "val33");
System.out.println(map.get(3)); // null
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9concat
}
private static <T> void testComputeIfPresent(Map<T, T> map, String desc, T[] keys,
BiFunction<T, T, T> mappingFunction) {
// remove a third of the keys
// call testComputeIfPresent for all keys[]
// removed keys should remain absent, even keys should be mapped to $RESULT
// no value from keys[] should be in map
T funcResult = mappingFunction.apply(keys[0], keys[0]);
int expectedSize1 = 0;
removeThirdKeys(map, keys);
for (int i = 0; i < keys.length; i++) {
T retVal = map.computeIfPresent(keys[i], mappingFunction);
if (i % 3 != 2) { // key present
if (funcResult == null) { // was removed
assertFalse(map.containsKey(keys[i]),
String.format("replaceIfMapped: containsKey(%s[%d])", desc, i));
} else { // value was replaced
assertTrue(map.containsKey(keys[i]),
String.format("replaceIfMapped: containsKey(%s[%d])", desc, i));
expectedSize1++;
}
assertEquals(retVal, funcResult,
String.format("computeIfPresent: retVal(%s[%s])", desc, i));
assertEquals(funcResult, map.get(keys[i]),
String.format("replaceIfMapped: get(%s[%d])", desc, i));
} else { // odd: was removed, should not be replaced
assertNull(retVal,
String.format("replaceIfMapped: retVal(%s[%d])", desc, i));
assertNull(map.get(keys[i]),
String.format("replaceIfMapped: get(%s[%d])", desc, i));
assertFalse(map.containsKey(keys[i]),
String.format("replaceIfMapped: containsKey(%s[%d])", desc, i));
}
assertFalse(map.containsValue(keys[i]),
String.format("replaceIfMapped: !containsValue(%s[%d])", desc, i));
}
assertEquals(map.size(), expectedSize1,
String.format("map expected size#1 m%d != k%d", map.size(), expectedSize1));
}
private static void addClassReference(
StoreTransaction txn,
Entity mainEntity,
Map<String, ClassIndex> classIndex,
Entity entity,
String fqcn) {
if (isNull(fqcn)) {
return;
}
classIndex.computeIfPresent(
fqcn,
(key, index) -> {
try {
EntityId entityId = index.getEntityId();
if (nonNull(entityId)) {
Entity classEntity = txn.getEntity(entityId);
classEntity.addLink(LINK_CLASS_REFERENCES, entity);
entity.addLink(LINK_CLASS, classEntity);
mainEntity.addLink(LINK_REV_CLASS_REFERENCES, entity);
}
} catch (Exception e) {
log.warn(e.getMessage());
}
return index;
});
}
private Map<String, Object> getConstraintAttributes() {
Map<String, Object> attributes = new HashMap<>(violation.getConstraintDescriptor().getAttributes());
attributes.computeIfPresent("groups", ValidationFailedGraphQLError::classNames);
attributes.computeIfPresent("payload", ValidationFailedGraphQLError::classNames);
return attributes;
}
@Test(timeout = 30000)
public void testListStreams() throws Exception {
final String scope = "test";
final String streamName1 = "test1";
final String streamName2 = "test2";
final String streamName3 = "test3";
final Map<String, Integer> foundCount = new HashMap<>();
foundCount.put(streamName1, 0);
foundCount.put(streamName2, 0);
foundCount.put(streamName3, 0);
foundCount.put(NameUtils.getMarkStreamForStream(streamName1), 0);
foundCount.put(NameUtils.getMarkStreamForStream(streamName2), 0);
foundCount.put(NameUtils.getMarkStreamForStream(streamName3), 0);
StreamConfiguration config = StreamConfiguration.builder()
.scalingPolicy(ScalingPolicy.byEventRate(10, 2, 1))
.build();
@Cleanup
Controller controller = controllerWrapper.getController();
@Cleanup
ConnectionFactory connectionFactory = new ConnectionFactoryImpl(ClientConfig.builder()
.controllerURI(URI.create("tcp://localhost"))
.build());
controllerWrapper.getControllerService().createScope(scope).get();
controller.createStream(scope, streamName1, config).get();
controller.createStream(scope, streamName2, config).get();
controller.createStream(scope, streamName3, config).get();
StreamManager manager = new StreamManagerImpl(controller, connectionFactory);
Iterator<Stream> iterator = manager.listStreams(scope);
assertTrue(iterator.hasNext());
Stream next = iterator.next();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
assertTrue(iterator.hasNext());
next = iterator.next();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
assertTrue(iterator.hasNext());
next = iterator.next();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
assertTrue(iterator.hasNext());
next = iterator.next();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
assertTrue(iterator.hasNext());
next = iterator.next();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
assertTrue(iterator.hasNext());
next = iterator.next();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
assertFalse(iterator.hasNext());
assertTrue(foundCount.entrySet().stream().allMatch(x -> x.getValue() == 1));
AsyncIterator<Stream> asyncIterator = controller.listStreams(scope);
next = asyncIterator.getNext().join();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
next = asyncIterator.getNext().join();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
next = asyncIterator.getNext().join();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
next = asyncIterator.getNext().join();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
next = asyncIterator.getNext().join();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
next = asyncIterator.getNext().join();
foundCount.computeIfPresent(next.getStreamName(), (x, y) -> ++y);
next = asyncIterator.getNext().join();
assertNull(next);
assertTrue(foundCount.entrySet().stream().allMatch(x -> x.getValue() == 2));
}
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));
map.computeIfPresent(3, (num, val) -> val + num);
System.out.println(map.get(3)); // val33
map.computeIfPresent(9, (num, val) -> null);
System.out.println(map.containsKey(9)); // false
map.computeIfAbsent(23, num -> "val" + num);
System.out.println(map.containsKey(23)); // true
map.computeIfAbsent(3, num -> "bam");
System.out.println(map.get(3)); // val33
System.out.println(map.getOrDefault(42, "not found")); // not found
map.remove(3, "val3");
System.out.println(map.get(3)); // val33
map.remove(3, "val33");
System.out.println(map.get(3)); // null
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
System.out.println(map.get(9)); // val9concat
}