本文整理汇总了Java中java.util.HashMap.putIfAbsent方法的典型用法代码示例。如果您正苦于以下问题:Java HashMap.putIfAbsent方法的具体用法?Java HashMap.putIfAbsent怎么用?Java HashMap.putIfAbsent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.HashMap
的用法示例。
在下文中一共展示了HashMap.putIfAbsent方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: callApi
import java.util.HashMap; //导入方法依赖的package包/类
/**
* Calls an elasticsearch api with the parameters and request body provided as arguments.
* Saves the obtained response in the execution context.
*/
public ClientYamlTestResponse callApi(String apiName, Map<String, String> params, List<Map<String, Object>> bodies,
Map<String, String> headers) throws IOException {
//makes a copy of the parameters before modifying them for this specific request
HashMap<String, String> requestParams = new HashMap<>(params);
requestParams.putIfAbsent("error_trace", "true"); // By default ask for error traces, this my be overridden by params
for (Map.Entry<String, String> entry : requestParams.entrySet()) {
if (stash.containsStashedValue(entry.getValue())) {
entry.setValue(stash.getValue(entry.getValue()).toString());
}
}
HttpEntity entity = createEntity(bodies, headers);
try {
response = callApiInternal(apiName, requestParams, entity, headers);
return response;
} catch(ClientYamlTestResponseException e) {
response = e.getRestTestResponse();
throw e;
} finally {
// if we hit a bad exception the response is null
Object responseBody = response != null ? response.getBody() : null;
//we always stash the last response body
stash.stashValue("body", responseBody);
}
}
示例2: buyIceCream
import java.util.HashMap; //导入方法依赖的package包/类
public static void buyIceCream(int [] costs, int money) {
HashMap<Integer, Integer> map = new HashMap<>(); // key = cost, value = ice cream ID
for (int i = 0; i < costs.length; i++) {
int icecreamID = i + 1;
int cost = costs[i];
/* Find 2 flavors to buy that sum to "money" */
int otherCost = money - cost;
if (map.containsKey(otherCost)) {
System.out.println(map.get(otherCost) + " " + icecreamID);
}
map.putIfAbsent(cost, icecreamID);
}
}
示例3: distinctByPredicate
import java.util.HashMap; //导入方法依赖的package包/类
/**
* Returns an immutable set containing each of elements, minus duplicates, in the order each
* appears first in the source collection.
*
* <p>Comparison (equals() and hashCode()) are performed on key.apply(X) instead of on X.
*/
private <T, S> ImmutableSet<T> distinctByPredicate(
Iterable<? extends T> items, Function<T, S> key) {
HashMap<S, T> m = new HashMap<>();
for (T item : items) {
m.putIfAbsent(key.apply(item), item);
}
return ImmutableSet.copyOf(m.values());
}