本文整理匯總了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());
}