下面列出了java.util.Map#compute ( ) 实例代码,或者点击链接到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 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));
}
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;
}
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())));
}
/**
* 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();
}
@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 @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);
});
}
@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();
}
}
}
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;
});
}
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;
});
}
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;
}
/**
* 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;
}
/**
* 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;
}
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.");
}
}
}
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) {}
}
@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);
}
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;
});
}
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;
});
}
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;
});
}
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);
}
}
private void processResource(FHIRRegistryResource registryResource, Map<String,Set<Canonical>> resourceTypeWithCanonicalUrls) {
String type = registryResource.getType();
resourceTypeWithCanonicalUrls.compute(type, (k,v) -> checkOrCreateSet(k,v,registryResource));
}