本文整理汇总了Java中java.util.Map.computeIfAbsent方法的典型用法代码示例。如果您正苦于以下问题:Java Map.computeIfAbsent方法的具体用法?Java Map.computeIfAbsent怎么用?Java Map.computeIfAbsent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.Map
的用法示例。
在下文中一共展示了Map.computeIfAbsent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createTransportMap
import java.util.Map; //导入方法依赖的package包/类
protected Map<String, List<CacheEndpoint>> createTransportMap() {
Map<String, List<CacheEndpoint>> transportMap = new HashMap<>();
for (MicroserviceInstance instance : instanceMap.values()) {
// 过滤到不可用实例
if (instance.getStatus() != MicroserviceInstanceStatus.UP) {
continue;
}
for (String endpoint : instance.getEndpoints()) {
try {
URI uri = URI.create(endpoint);
String transportName = uri.getScheme();
List<CacheEndpoint> cacheEndpointList = transportMap.computeIfAbsent(transportName, k -> new ArrayList<>());
cacheEndpointList.add(new CacheEndpoint(endpoint, instance));
} catch (Exception e) {
LOGGER.warn("unrecognized address find, ignore " + endpoint);
}
}
}
return transportMap;
}
示例2: sum
import java.util.Map; //导入方法依赖的package包/类
/**
* Sum collection of ResultAndUpdate into one: results are reduced by specified binary operator and updates are merged.
*
* @param reducer Reducer used to combine computation results.
* @param resultsAndUpdates ResultAndUpdates to be combined with.
* @param <R> Type of computation result.
* @return Sum of collection ResultAndUpdate objects.
*/
@SuppressWarnings("unchecked")
static <R> ResultAndUpdates<R> sum(IgniteFunction<List<R>, R> reducer,
Collection<ResultAndUpdates<R>> resultsAndUpdates) {
Map<String, Map> allUpdates = new HashMap<>();
for (ResultAndUpdates<R> ru : resultsAndUpdates) {
for (String cacheName : ru.updates.keySet()) {
allUpdates.computeIfAbsent(cacheName, s -> new HashMap());
allUpdates.get(cacheName).putAll(ru.updates.get(cacheName));
}
}
List<R> results = resultsAndUpdates.stream().map(ResultAndUpdates::result).collect(Collectors.toList());
return new ResultAndUpdates<>(reducer.apply(results), allUpdates);
}
示例3: computeIfAbsent
import java.util.Map; //导入方法依赖的package包/类
/**
* An unsafe version of {@link Map#computeIfAbsent(Object, Function) Map.computeIfAbsent} that may throw a checked
* exception.
*
* @param map the map to modify
* @param key the key to get
* @param function the compute function
* @param <K> the type of keys in the map
* @param <V> the type of values in the map
* @param <X> the type of exception that the compute function may throw
*
* @return
*
* @throws X if the compute function threw an exception
*/
public static <K, V, X extends Throwable> V computeIfAbsent(
Map<K, V> map, K key, ThrowingFunction<? super K, ? extends V, ? extends X> function) throws X {
Throwable[] exception = {null};
final Object none = new Object();
V value = map.computeIfAbsent(key, k -> {
try {
return function.apply(k);
} catch (Throwable e) {
exception[0] = e;
return (V) none;
}
});
if (value == none) { // NOPMD reference equality check
throw (X) exception[0];
} else {
return value;
}
}
示例4: productNameForInvoiceItem
import java.util.Map; //导入方法依赖的package包/类
private String productNameForInvoiceItem(final InvoiceItem invoiceItem,
final Map<String, String> planToProductCache, final UUID kbTenantId) {
final String planName = invoiceItem.getPlanName();
if (planName == null) {
return null;
}
return planToProductCache.computeIfAbsent(planName, k -> {
try {
StaticCatalog catalog = killbillApi.getCatalogUserApi().getCurrentCatalog(null,
new EasyTaxTenantContext(kbTenantId, invoiceItem.getAccountId()));
Plan plan = catalog.findCurrentPlan(planName);
return (plan != null && plan.getProduct() != null ? plan.getProduct().getName()
: null);
} catch (CatalogApiException e) {
return null;
}
});
}
示例5: checkForDuplicatePkgs
import java.util.Map; //导入方法依赖的package包/类
/**
* Checks a configuration and the module-to-loader mapping to ensure that
* no two modules mapped to the same class loader have the same package.
* It also checks that no two automatic modules have the same package.
*
* @throws LayerInstantiationException
*/
private static void checkForDuplicatePkgs(Configuration cf,
Function<String, ClassLoader> clf)
{
// HashMap allows null keys
Map<ClassLoader, Set<String>> loaderToPackages = new HashMap<>();
for (ResolvedModule resolvedModule : cf.modules()) {
ModuleDescriptor descriptor = resolvedModule.reference().descriptor();
ClassLoader loader = clf.apply(descriptor.name());
Set<String> loaderPackages
= loaderToPackages.computeIfAbsent(loader, k -> new HashSet<>());
for (String pkg : descriptor.packages()) {
boolean added = loaderPackages.add(pkg);
if (!added) {
throw fail("More than one module with package %s mapped" +
" to the same class loader", pkg);
}
}
}
}
示例6: findPendingSagaEvents
import java.util.Map; //导入方法依赖的package包/类
@Override
public Map<String, List<EventEnvelope>> findPendingSagaEvents() {
List<SagaEventEntity> events = repo.findIncompleteSagaEventsGroupBySagaId();
Map<String, List<EventEnvelope>> pendingEvents = new HashMap<>();
for (SagaEventEntity event : events) {
pendingEvents.computeIfAbsent(event.sagaId(), id -> new LinkedList<>());
pendingEvents.get(event.sagaId()).add(
new EventEnvelope(
event.id(),
event.creationTime(),
sagaEventFormat.toSagaEvent(event.sagaId(), event.type(), event.contentJson())));
}
return pendingEvents;
}
示例7: mapRpcs
import java.util.Map; //导入方法依赖的package包/类
public Rpcs mapRpcs() {
final Map<String, Map<String, ModuleRpcs>> map = new HashMap<>();
for (final Map.Entry<String, Map<String, ModuleMXBeanEntry>> namespaceToModuleEntry : yangStoreService
.getModuleMXBeanEntryMap().entrySet()) {
Map<String, ModuleRpcs> namespaceToModules = map.computeIfAbsent(namespaceToModuleEntry.getKey(),
k -> new HashMap<>());
for (final Map.Entry<String, ModuleMXBeanEntry> moduleEntry : namespaceToModuleEntry.getValue()
.entrySet()) {
ModuleRpcs rpcMapping = namespaceToModules.computeIfAbsent(moduleEntry.getKey(),
k -> new ModuleRpcs(yangStoreService.getEnumResolver()));
final ModuleMXBeanEntry entry = moduleEntry.getValue();
for (final RuntimeBeanEntry runtimeEntry : entry.getRuntimeBeans()) {
rpcMapping.addNameMapping(runtimeEntry);
for (final RuntimeBeanEntry.Rpc rpc : runtimeEntry.getRpcs()) {
rpcMapping.addRpc(runtimeEntry, rpc);
}
}
}
}
return new Rpcs(map);
}
示例8: getComputedValue
import java.util.Map; //导入方法依赖的package包/类
/**
* Retrieve the computed value for specified parameters, creating it if necessary.
*
* @param args the arguments passed to the memoized function.
*/
@SuppressWarnings( "unchecked" )
private ComputedValue<T> getComputedValue( @Nonnull final Object... args )
{
apiInvariant( () -> args.length == _argCount,
() -> "MemoizeCache.getComputedValue called with " + args.length + " arguments but expected " +
_argCount + " arguments." );
Map<Object, Object> map = _cache;
final int size = args.length - 1;
for ( int i = 0; i < size; i++ )
{
map = (Map<Object, Object>) map.computeIfAbsent( args[ i ], v -> new HashMap<>() );
}
return (ComputedValue<T>) map.computeIfAbsent( args[ size ], v -> createComputedValue( args ) );
}
示例9: add
import java.util.Map; //导入方法依赖的package包/类
/**
* Adjust the Class Tree. Add the class interface in to it's super classes
* or super interface's sub-interface set.
*
* @param map the entire map.
* @param superclass java.lang.Object or the super-interface.
* @param typeElement sub-interface to be mapped.
* @returns boolean true if class added, false if class already processed.
*/
private boolean add(Map<TypeElement, SortedSet<TypeElement>> map, TypeElement superclass, TypeElement typeElement) {
SortedSet<TypeElement> sset = map.computeIfAbsent(superclass, s -> new TreeSet<>(comparator));
if (sset.contains(typeElement)) {
return false;
} else {
sset.add(typeElement);
}
return true;
}
示例10: validateGitHubRepositoryExists
import java.util.Map; //导入方法依赖的package包/类
public void validateGitHubRepositoryExists(UIValidationContext context, String repository) {
Map<Object, Object> attributeMap = context.getUIContext().getAttributeMap();
String validationMessage = (String) attributeMap.computeIfAbsent("validate_repo_" + repository, key -> {
List<String> authList = (List<String>) attributeMap.get(HttpHeaders.AUTHORIZATION);
String authHeader = (authList == null || authList.isEmpty()) ? null : authList.get(0);
return missionControlFacade.validateGitHubRepositoryExists(authHeader, repository);
});
if (validationMessage != null && !MissionControl.VALIDATION_MESSAGE_OK.equals(validationMessage)) {
context.addValidationError(context.getCurrentInputComponent(), validationMessage);
}
}
示例11: validateOpenShiftProjectExists
import java.util.Map; //导入方法依赖的package包/类
public void validateOpenShiftProjectExists(UIValidationContext context, String project, String cluster) {
Map<Object, Object> attributeMap = context.getUIContext().getAttributeMap();
String validationMessage = (String) attributeMap.computeIfAbsent("validate_project_" + project, key -> {
List<String> authList = (List<String>) attributeMap.get(HttpHeaders.AUTHORIZATION);
String authHeader = (authList == null || authList.isEmpty()) ? null : authList.get(0);
return missionControlFacade.validateOpenShiftProjectExists(authHeader, project, cluster);
});
if (validationMessage != null && !MissionControl.VALIDATION_MESSAGE_OK.equals(validationMessage)) {
context.addValidationWarning(context.getCurrentInputComponent(), validationMessage);
}
}
示例12: installRegion
import java.util.Map; //导入方法依赖的package包/类
/**
* Install a new region.
*/
private ProvLocation installRegion(final Map<String, ProvLocation> regions, final String region, final Node node) {
return regions.computeIfAbsent(region, r -> {
final ProvLocation location = new ProvLocation();
location.setNode(node);
location.setName(r);
locationRepository.saveAndFlush(location);
return location;
});
}
示例13: addStatesToGlobalMapForMethod
import java.util.Map; //导入方法依赖的package包/类
private void addStatesToGlobalMapForMethod(
DexEncodedMethod method, Set<NamingState<DexProto>> collectedStates,
Map<Wrapper<DexMethod>, Set<NamingState<DexProto>>> globalStateMap,
Map<Wrapper<DexMethod>, Set<DexMethod>> sourceMethodsMap,
Map<Wrapper<DexMethod>, NamingState<DexProto>> originStates, DexType originInterface) {
Wrapper<DexMethod> key = equivalence.wrap(method.method);
Set<NamingState<DexProto>> stateSet =
globalStateMap.computeIfAbsent(key, k -> new HashSet<>());
stateSet.addAll(collectedStates);
sourceMethodsMap.computeIfAbsent(key, k -> new HashSet<>()).add(method.method);
originStates.putIfAbsent(key, states.get(originInterface));
}
示例14: detectCyclesInEntityGraph
import java.util.Map; //导入方法依赖的package包/类
/**
* Inspects the instance graph for cycles, any cycle is printed as an error. The nameToEntity parameter doesn't list expected
* instances, any instances that are not found in the nameToInstances map (they are looked for because they are referenced as a
* dependency by an instance in the map) and are not found by name in the definition's expectedInstances are treated as errors
* as well.
*
* @param definition definition being processed. Will uses it's expected list, any instances references as dependencies but
* not found, not listed as expected in this DefinitionModel, will be treated as errors.
* @param nameToEntity name to unique instanceModels, verified before call.
* @param errorListner accepts and displays all errors produced by analyzing the models
* @return true if an error occurred, false otherwise
*/
private boolean detectCyclesInEntityGraph(final DefinitionModel definition, final Map<String, InstanceModel> nameToEntity,
final Consumer<ErrorModel> errorListener) {
final Map<String, ExpectedModel> missing = new HashMap<>();
final DirectedGraph<BaseInstanceModel, DefaultEdge> entityGraph = new DefaultDirectedGraph<>(DefaultEdge.class);
for (BaseInstanceModel entity : nameToEntity.values()) {
if (!entityGraph.containsVertex(entity)) {
entityGraph.addVertex(entity);
}
if (InstanceModel.class.isAssignableFrom(entity.getClass())) {
InstanceModel instanceModel = (InstanceModel) entity;
for (InstanceDependencyModel instanceDependency : instanceModel.getDependencies()) {
BaseInstanceModel dependency = nameToEntity.get(instanceDependency.getIdentity());
if (dependency == null) {
dependency = missing.computeIfAbsent(instanceDependency.getIdentity(), s -> new ExpectedModel(s));
missing.get(instanceDependency.getIdentity())
.addDefinitionReferenceToType(instanceModel.getIdentity(), instanceDependency.getType());
}
if (!entityGraph.containsVertex(dependency)) {
entityGraph.addVertex(dependency);
}
entityGraph.addEdge(entity, dependency);
}
}
}
boolean errored = errorsForCycles(errorListener, entityGraph);
errored = testAllMissingEntitiesAreExpected(definition, errorListener, missing, entityGraph) || errored;
errored = errorUnusedExpectedsOnDefinition(definition, errorListener, missing) || errored;
return errored;
}
示例15: reducedSuggest
import java.util.Map; //导入方法依赖的package包/类
private Suggest reducedSuggest(AtomicArray<QuerySearchResultProvider> results) {
Map<String, List<Suggest.Suggestion<CompletionSuggestion.Entry>>> groupedSuggestion = new HashMap<>();
for (AtomicArray.Entry<QuerySearchResultProvider> entry : results.asList()) {
for (Suggest.Suggestion<?> suggestion : entry.value.queryResult().suggest()) {
List<Suggest.Suggestion<CompletionSuggestion.Entry>> suggests =
groupedSuggestion.computeIfAbsent(suggestion.getName(), s -> new ArrayList<>());
suggests.add((Suggest.Suggestion<CompletionSuggestion.Entry>) suggestion);
}
}
return new Suggest(groupedSuggestion.values().stream().map(CompletionSuggestion::reduceTo)
.collect(Collectors.toList()));
}