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

The following examples show how to use java.util.Map#compute() . 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 File: ExpirationTest.java    From caffeine with 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 compute_writeTime(Map<Integer, Integer> map, CacheContext context) {
  Integer key = context.firstKey();
  Integer value = context.absentValue();

  map.compute(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 File: Strings.java    From Java-Coding-Problems with MIT License 6 votes vote down vote up
public static char firstNonRepeatedCharacterV3(String str) {

        if (str == null || str.isBlank()) {
            // or throw IllegalArgumentException
            return Character.MIN_VALUE;
        }

        Map<Character, Integer> chars = new LinkedHashMap<>();

        // or use for(char ch: str.toCharArray()) { ... }
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            chars.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
        }

        for (Map.Entry<Character, Integer> entry : chars.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }

        return Character.MIN_VALUE;
    }
 
Example 3
Source File: TreeNode.java    From LuckPerms with MIT License 6 votes vote down vote up
public @Nullable TreeNode tryInsert(String s) {
    Map<String, TreeNode> childMap = getChildMap();
    if (!allowInsert(this)) {
        return null;
    }

    return childMap.compute(s, (key, prev) -> {
        if (prev != null) {
            return prev;
        }

        // dirty the cache & return a new node
        this.cachedDeepSize = Integer.MIN_VALUE;
        return new TreeNode(this);
    });
}
 
Example 4
Source File: WordPosFrequencies.java    From biomedicus with Apache License 2.0 6 votes vote down vote up
Map<Integer, WordPosFrequencies> byWordLength() {
  Map<Integer, Map<String, Map<PartOfSpeech, Integer>>> builder = new HashMap<>();
  for (String s : getWords()) {
    int length = s.length();
    builder.compute(length, (Integer k, @Nullable Map<String, Map<PartOfSpeech, Integer>> v) -> {
      if (v == null) {
        v = new HashMap<>();
      }
      v.put(s, posFrequenciesForWord.get(s));
      return v;
    });
  }
  return builder.entrySet()
      .stream()
      .collect(Collectors.toMap(Map.Entry::getKey, e -> bySumming(e.getValue())));
}
 
Example 5
Source File: Java78Test.java    From onetwo with 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 6
Source File: ServiceInfo.java    From armeria with Apache License 2.0 6 votes vote down vote up
/**
 * Merges the {@link MethodInfo}s with the same method name and {@link HttpMethod} pair
 * into a single {@link MethodInfo}. Note that only the {@link EndpointInfo}s are merged
 * because the {@link MethodInfo}s being merged always have the same
 * {@code exampleHttpHeaders} and {@code exampleRequests}.
 */
@VisibleForTesting
static Set<MethodInfo> mergeEndpoints(Iterable<MethodInfo> methodInfos) {
    final Map<List<Object>, MethodInfo> methodInfoMap = new HashMap<>();
    for (MethodInfo methodInfo : methodInfos) {
        final List<Object> mergeKey = ImmutableList.of(methodInfo.name(), methodInfo.httpMethod());
        methodInfoMap.compute(mergeKey, (key, value) -> {
            if (value == null) {
                return methodInfo;
            } else {
                final Set<EndpointInfo> endpointInfos =
                        Sets.union(value.endpoints(), methodInfo.endpoints());
                return new MethodInfo(value.name(), value.returnTypeSignature(),
                                      value.parameters(), value.exceptionTypeSignatures(),
                                      endpointInfos, value.exampleHttpHeaders(),
                                      value.exampleRequests(), value.examplePaths(), value.exampleQueries(),
                                      value.httpMethod(), value.docString());
            }
        });
    }
    return ImmutableSortedSet
            .orderedBy(comparing(MethodInfo::name).thenComparing(MethodInfo::httpMethod))
            .addAll(methodInfoMap.values())
            .build();
}
 
Example 7
Source File: MultiValueMapUtils.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public static <K, V> void add(Map<K, Collection<V>> multiMap, K key, V value) {
  multiMap.compute(key, (key_, values_) -> {
    Collection<V> valuesMerged = values_ != null ? values_ : new ArrayList<>(1);
    valuesMerged.add(value);
    return valuesMerged;
  });
}
 
Example 8
Source File: GearFeature.java    From MineLittlePony with MIT License 5 votes vote down vote up
@Override
public void render(MatrixStack stack, VertexConsumerProvider renderContext, int lightUv, T entity, float limbDistance, float limbAngle, float tickDelta, float age, float headYaw, float headPitch) {

    if (entity.isInvisible()) {
        return;
    }

    M model = getModelWrapper().getBody();

    Map<BodyPart, Float> renderStackingOffsets = new HashMap<>();

    for (Map.Entry<Wearable, IGear> entry : gears.entrySet()) {
        Wearable wearable = entry.getKey();
        IGear gear = entry.getValue();

        if (getContext().shouldRender(model, entity, wearable, gear)) {
            stack.push();
            model.transform(gear.getGearLocation(), stack);
            model.getBodyPart(gear.getGearLocation()).rotate(stack);

            if (gear instanceof IStackable) {
                BodyPart part = gear.getGearLocation();
                renderStackingOffsets.compute(part, (k, v) -> {
                    float offset = ((IStackable)gear).getStackingOffset();
                    if (v != null) {
                        stack.translate(0, -v, 0);
                        offset += v;
                    }
                    return offset;
                });
            }

            renderGear(model, entity, gear, stack, renderContext, lightUv, limbDistance, limbAngle, tickDelta);
            stack.pop();
        }
    }
}
 
Example 9
Source File: MultiValueMapUtils.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public static <K, V> void addAll(Map<K, Collection<V>> multiMap, K key, Collection<V> values) {
  multiMap.compute(key, (key_, values_) -> {
    Collection<V> valuesMerged = values_ != null ? values_ : new ArrayList<>(values.size());
    valuesMerged.addAll(values);
    return valuesMerged;
  });
}
 
Example 10
Source File: MultiValueMapUtils.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public static <K, V> void addOrdered(Map<K, List<V>> multiMap, K key, V value) {
  multiMap.compute(key, (key_, values_) -> {
    List<V> valuesMerged = values_ != null ? values_ : new ArrayList<>(1);
    valuesMerged.add(value);
    return valuesMerged;
  });
}
 
Example 11
Source File: AmortizedMaintenanceCounterTest.java    From macrobase with Apache License 2.0 5 votes vote down vote up
@Test
public void decayTest() {
    final int N = 1000;
    final int ITEMS = 100;
    final double DECAY = .5;
    final int CAPACITY = 15;
    final double EPSILON = 1.0/CAPACITY;

    AmortizedMaintenanceCounter ss = new AmortizedMaintenanceCounter(CAPACITY);

    Random r = new Random(0);

    Map<Integer, Double> trueCnt = new HashMap<>();

    for (int i = 0; i < N; ++i) {
        int item = r.nextInt(ITEMS);
        ss.observe(item);

        trueCnt.compute(item, (k, v) -> v == null ? 1 : v + 1);

        if (i % 10 == 0) {
            ss.multiplyAllCounts(DECAY);

            trueCnt.forEach((k, v) -> trueCnt.put(k, v*DECAY));
        }
    }

    Map<Integer, Double> cnts = ss.getCounts();

    for (Map.Entry<Integer, Double> cnt : cnts.entrySet()) {
        assertEquals(trueCnt.get(cnt.getKey()), cnt.getValue(), N*EPSILON);
    }

    int key = cnts.keySet().iterator().next();
    assertEquals(cnts.get(key), ss.getCount(key), 1e-10);
}
 
Example 12
Source File: CollectionsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_CheckedMap_compute() {
    Map<Integer, Double> map = new HashMap<>();
    Map checkedMap = Collections.checkedMap(map, Integer.class, Double.class);
    MapDefaultMethodTester.test_compute(checkedMap, true /* acceptsNullKey */);

    Map checkedMap2 = Collections.checkedMap(new HashMap(), Integer.class, String.class);
    checkedMap2.put(1, A_STRING);
    try {
        checkedMap2.compute(1, (k, v) -> NOT_A_STRING);
        fail();
    } catch (ClassCastException expected) {}
}
 
Example 13
Source File: GraphComparator.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
private void shouldBeEmpty(final Graph<Node, Edge> givenGraph, final AssertionErrorCollector errorCollector) {
    final Map<String, Integer> unexpectedNodesOccurence = new HashMap<>();

    for (final Node node : givenGraph.vertexSet()) {
        unexpectedNodesOccurence.compute(node.getType(), (k, v) -> v == null ? 1 : v + 1);
    }

    for (final Entry<String, Integer> nodeEntries : unexpectedNodesOccurence.entrySet()) {
        if (nodeEntries.getValue() != 0) {
            errorCollector.collect("No nodes with " + nodeEntries.getKey() + " labels were expected, but there are <"
                    + nodeEntries.getValue() + "> nodes present.");
        }
    }
}
 
Example 14
Source File: ChainResolver.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves all keys within the given chain to their equivalent put operations.
 *
 * @param chain target chain
 * @return a map of equivalent put operations
 */
protected Map<K, PutOperation<K, V>> resolveAll(Chain chain) {
  //absent hash-collisions this should always be a 1 entry map
  Map<K, PutOperation<K, V>> compacted = new HashMap<>(2);
  for (Element element : chain) {
    ByteBuffer payload = element.getPayload();
    Operation<K, V> operation = codec.decode(payload);
    compacted.compute(operation.getKey(), (k, v) -> applyOperation(k, v, operation));
  }
  return compacted;
}
 
Example 15
Source File: ModelZoo.java    From djl with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the available {@link Application} and their model artifact metadata.
 *
 * @return the available {@link Application} and their model artifact metadata
 * @throws IOException if failed to download to repository metadata
 * @throws ModelNotFoundException if failed to parse repository metadata
 */
static Map<Application, List<Artifact>> listModels()
        throws IOException, ModelNotFoundException {
    @SuppressWarnings("PMD.UseConcurrentHashMap")
    Map<Application, List<Artifact>> models =
            new TreeMap<>(Comparator.comparing(Application::getPath));
    ServiceLoader<ZooProvider> providers = ServiceLoader.load(ZooProvider.class);
    for (ZooProvider provider : providers) {
        ModelZoo zoo = provider.getModelZoo();
        if (zoo == null) {
            continue;
        }
        List<ModelLoader<?, ?>> list = zoo.getModelLoaders();
        for (ModelLoader<?, ?> loader : list) {
            Application app = loader.getApplication();
            final List<Artifact> artifacts = loader.listModels();
            models.compute(
                    app,
                    (key, val) -> {
                        if (val == null) {
                            val = new ArrayList<>();
                        }
                        val.addAll(artifacts);
                        return val;
                    });
        }
    }
    return models;
}
 
Example 16
Source File: EMailComponent.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> bundleOptions() {
    Map<String, Object> options = new HashMap<>();
    options.compute(PROTOCOL, value(this::getProtocol));
    options.compute(SECURE_TYPE, value(this::getSecureType));
    options.compute(HOST, value(this::getHost));
    options.compute(PORT, value(this::getPort));
    options.compute(USER, value(this::getUsername));
    options.compute(PASSWORD, value(this::getPassword));
    options.compute(FOLDER, value(this::getFolderName));
    options.compute(SERVER_CERTIFICATE, value(this::getServerCertificate));
    options.compute(UNSEEN_ONLY, value(this::isUnseenOnly));
    options.compute(DELAY, value(this::getDelay));
    options.compute(MAX_MESSAGES, value(this::getMaxResults));
    return options;
}
 
Example 17
Source File: MultiValueMapUtils.java    From feign-reactive with Apache License 2.0 5 votes vote down vote up
public static <K, V> void addAllOrdered(Map<K, List<V>> multiMap, K key, List<V> values) {
  multiMap.compute(key, (key_, values_) -> {
    List<V> valuesMerged = values_ != null ? values_ : new ArrayList<>(values.size());
    valuesMerged.addAll(values);
    return valuesMerged;
  });
}
 
Example 18
Source File: ConceptDictionaryBuilder.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
private <K, V> void multimapPut(Map<K, List<V>> map, K key, V value) {
  map.compute(key, (unused, v) -> {
    if (v == null) {
      v = new ArrayList<>();
    }
    v.add(value);
    return v;
  });
}
 
Example 19
Source File: FHIRRegistry.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private void processResource(FHIRRegistryResource registryResource, Map<String,Set<Canonical>> resourceTypeWithCanonicalUrls) {
    String type = registryResource.getType();
    resourceTypeWithCanonicalUrls.compute(type, (k,v) -> checkOrCreateSet(k,v,registryResource));
}
 
Example 20
Source File: ArticulationPoint.java    From interview with Apache License 2.0 4 votes vote down vote up
private void DFS(Set<Vertex<T>> visited,
        Set<Vertex<T>> articulationPoints, Vertex<T> vertex,
        Map<Vertex<T>, Integer> visitedTime,
        Map<Vertex<T>, Integer> lowTime, Map<Vertex<T>, Vertex<T>> parent) {
    visited.add(vertex);
    visitedTime.put(vertex, time);
    lowTime.put(vertex, time);
    time++;
    int childCount =0;
    boolean isArticulationPoint = false;
    for(Vertex<T> adj : vertex.getAdjacentVertexes()){
        //if adj is same as parent then just ignore this vertex.
        if(adj.equals(parent.get(vertex))) {
            continue;
        }
        //if adj has not been visited then visit it.
        if(!visited.contains(adj)) {
            parent.put(adj, vertex);
            childCount++;
            DFS(visited, articulationPoints, adj, visitedTime, lowTime, parent);

            if(visitedTime.get(vertex) <= lowTime.get(adj)) {
                isArticulationPoint = true;
            } else {
                //below operation basically does lowTime[vertex] = min(lowTime[vertex], lowTime[adj]);
                lowTime.compute(vertex, (currentVertex, time) ->
                    Math.min(time, lowTime.get(adj))
                );
            }

        } else { //if adj is already visited see if you can get better low time.
            //below operation basically does lowTime[vertex] = min(lowTime[vertex], visitedTime[adj]);
            lowTime.compute(vertex, (currentVertex, time) ->
                            Math.min(time, visitedTime.get(adj))
            );
        }
    }

    //checks if either condition 1 or condition 2 meets). If yes then it is articulation point.
    if((parent.get(vertex) == null && childCount >= 2) || parent.get(vertex) != null && isArticulationPoint ) {
        articulationPoints.add(vertex);
    }
    
}