Java Code Examples for java.util.Map#computeIfPresent()

The following examples show how to use java.util.Map#computeIfPresent() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: caffeine   File: ExpirationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example 2
Source Project: onetwo   File: Java78Test.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 3
Source Project: garmadon   File: GarmadonMessage.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source Project: caffeine   File: ExpirationTest.java    License: Apache License 2.0 6 votes vote down vote up
@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()));
  }
}
 
Example 5
Source Project: Javacord   File: DiscordApiImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 6
Source Project: onos   File: FlowBucket.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 7
Source Project: Javacord   File: DiscordApiImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 8
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;
}
 
Example 9
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);
}
 
Example 10
Source Project: j2objc   File: CollectionsTest.java    License: Apache License 2.0 5 votes vote down vote up
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) {}
}
 
Example 11
Source Project: caffeine   File: AsMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 12
/**
 * 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);
}
 
Example 13
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;
}
 
Example 14
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);
}
 
Example 15
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
}
 
Example 16
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));
}
 
Example 17
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;
      });
}
 
Example 18
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;
}
 
Example 19
Source Project: pravega   File: ScopeTest.java    License: Apache License 2.0 4 votes vote down vote up
@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));
}
 
Example 20
Source Project: java8-tutorial   File: Maps1.java    License: MIT License 3 votes vote down vote up
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
}