本文整理汇总了Java中java.util.Map.putIfAbsent方法的典型用法代码示例。如果您正苦于以下问题:Java Map.putIfAbsent方法的具体用法?Java Map.putIfAbsent怎么用?Java Map.putIfAbsent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.Map
的用法示例。
在下文中一共展示了Map.putIfAbsent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: demoMapPut
import java.util.Map; //导入方法依赖的package包/类
private static void demoMapPut(Map<Integer, String> map) {
System.out.println("map: " + map);
try {
Set<Integer> keys = map.keySet();
for (int i : keys) {
System.out.println(i);
System.out.println("Calling map.put(8, Eight)...");
map.put(8, "Eight");
System.out.println("map: " + map);
System.out.println("Calling map.put(8, Eight)...");
map.put(8, "Eight");
System.out.println("map: " + map);
System.out.println("Calling map.putIfAbsent(9, Nine)...");
map.putIfAbsent(9, "Nine");
System.out.println("map: " + map);
System.out.println("Calling map.putIfAbsent(9, Nine)...");
map.putIfAbsent(9, "Nine");
System.out.println("keys.size(): " + keys.size());
System.out.println("map: " + map);
}
} catch (Exception ex) {
System.out.println(ex.getClass().getName());
}
}
示例2: writeDictionaryToFileSystem
import java.util.Map; //导入方法依赖的package包/类
private static void writeDictionaryToFileSystem(CollectiveDictionary dict) throws FileNotFoundException {
PrintStream ps = new PrintStream(new File("gen/collectiveDiseaseDictionary"));
Map<Concept, Set<String>> d = new HashMap<>();
for (ISubDictionary subDict : dict.getDictionaries()) {
for (Entry<DictionaryEntry, Set<Concept>> sd : subDict.getDictionary().entrySet()) {
for (Concept concept : sd.getValue()) {
d.putIfAbsent(concept, new HashSet<>());
d.get(concept).add(sd.getKey().normalizedSurfaceForm);
}
}
}
d.entrySet().stream().map(c -> c.getKey().conceptID + "=" + c.getValue()).forEach(ps::println);
ps.close();
}
示例3: addNotified
import java.util.Map; //导入方法依赖的package包/类
private void addNotified(GrpcURL subscribedUrl, NotifyListener.NotifyServiceListener listener,
List<GrpcURL> providerUrls) {
Map<NotifyListener.NotifyServiceListener, List<GrpcURL>> notifiedUrlMap =
notified.get(subscribedUrl);
List<GrpcURL> notifiedUrlList;
if (notifiedUrlMap == null) {
notifiedUrlMap = Maps.newConcurrentMap();
notifiedUrlList = providerUrls;
} else {
notifiedUrlList = notifiedUrlMap.get(listener);
if (notifiedUrlList == null) {
notifiedUrlList = Lists.newArrayList();
}
notifiedUrlList.addAll(providerUrls);
}
notifiedUrlMap.putIfAbsent(listener, notifiedUrlList);
notified.putIfAbsent(subscribedUrl, notifiedUrlMap);
}
示例4: getPatches
import java.util.Map; //导入方法依赖的package包/类
@NonNull
public static Map<String,List<URL>> getPatches(@NonNull final CompilerOptionsQuery.Result res) {
Parameters.notNull("res", res); //NOI18N
final Map<String,List<URL>> patches = new HashMap<>();
boolean patch = false;
for (String arg : res.getArguments()) {
if (patch) {
//<module>=<file>(:<file>)*
final Matcher m = MATCHER_PATCH.matcher(arg);
if (m.matches() && m.groupCount() == 2) {
final String module = m.group(1);
final String path = m.group(2);
if (!module.isEmpty() && !path.isEmpty()) {
patches.putIfAbsent(
module,
Arrays.stream(PropertyUtils.tokenizePath(path))
.map((p) -> FileUtil.normalizeFile(new File(p)))
.map(FileUtil::urlForArchiveOrDir)
.collect(Collectors.toList()));
}
}
}
patch = ARG_PATCH_MOD.equals(arg);
}
return patches;
}
示例5: implAddOpensToAllUnnamed
import java.util.Map; //导入方法依赖的package包/类
/**
* Updates a module to open all packages returned by the given iterator to
* all unnamed modules.
*
* @apiNote Used during startup to open packages for illegal access.
*/
void implAddOpensToAllUnnamed(Iterator<String> iterator) {
if (jdk.internal.misc.VM.isModuleSystemInited()) {
throw new IllegalStateException("Module system already initialized");
}
// replace this module's openPackages map with a new map that opens
// the packages to all unnamed modules.
Map<String, Set<Module>> openPackages = this.openPackages;
if (openPackages == null) {
openPackages = new HashMap<>();
} else {
openPackages = new HashMap<>(openPackages);
}
while (iterator.hasNext()) {
String pn = iterator.next();
Set<Module> prev = openPackages.putIfAbsent(pn, ALL_UNNAMED_MODULE_SET);
if (prev != null) {
prev.add(ALL_UNNAMED_MODULE);
}
// update VM to export the package
addExportsToAllUnnamed0(this, pn);
}
this.openPackages = openPackages;
}
示例6: execute
import java.util.Map; //导入方法依赖的package包/类
@Override
protected void execute() {
Map<String, String> strMap = Maps.newHashMap();
strMap.putIfAbsent("name", name);
strMap.putIfAbsent("deviceOwner", deviceOwner);
strMap.putIfAbsent("bindingvnicType", bindingvnicType);
strMap.putIfAbsent("bindingvifType", bindingvifType);
strMap.putIfAbsent("bindingvnicDetails", bindingvnicDetails);
VirtualPortService service = get(VirtualPortService.class);
VirtualPort virtualPort = new DefaultVirtualPort(VirtualPortId.portId(id),
TenantNetworkId.networkId(networkId),
false, strMap, VirtualPort.State.ACTIVE,
MacAddress.valueOf(macAddress),
TenantId.tenantId(tenantId),
DeviceId.deviceId(deviceId), Sets.newHashSet(fixedIp),
BindingHostId.bindingHostId(bindingHostId),
allowedAddressPairs, securityGroups);
Set<VirtualPort> virtualPorts = Sets.newHashSet(virtualPort);
service.createPorts(virtualPorts);
}
示例7: addRowToMap
import java.util.Map; //导入方法依赖的package包/类
/**
* Adds a raw row (mapping from cycle number x variable name to cell expression as string) to the
* map for a given assignment from the solver that has the format (define-fun VarName_row_cycle ()
* SolverType SolverValue).
*
* @param durations list of concrete durations
* @param rawRows mapping from cycle number x variable name to cell expression as string
* @param varAssign solver assignment
*/
private static void addRowToMap(List<ConcreteDuration> durations,
Map<Integer, Map<String, String>> rawRows, Sexp varAssign) {
if (varAssign.getLength() == 0 || !varAssign.get(0).toIndentedString().equals("define-fun")) {
return;
}
Matcher identifierMatcher = VAR_PATTERN.matcher(varAssign.get(1).toIndentedString());
if (identifierMatcher.matches()) {
String varName = identifierMatcher.group("name");
String row = identifierMatcher.group("row");
String cycle = identifierMatcher.group("cycle");
// is variable
int cycleCount = Integer.parseInt(cycle);
// ignore variables if iteration > n_z
int nz = Integer.parseInt(row);
ConcreteDuration concreteDuration = durations.get(nz);
if (cycleCount >= concreteDuration.getDuration()) {
return;
}
int absoluteIndex = concreteDuration.getBeginCycle() + cycleCount;
rawRows.putIfAbsent(absoluteIndex, new HashMap<>());
rawRows.get(absoluteIndex).put(varName, varAssign.get(4).toIndentedString());
}
}
示例8: computeScore
import java.util.Map; //导入方法依赖的package包/类
@Override
public double computeScore(JLinkState resultState, JLinkState goldState) {
Map<String, Set<String>> gold = new HashMap<String, Set<String>>();
Map<String, Set<String>> result = new HashMap<String, Set<String>>();
/*
* Split to get on documents name level instead of the sentence level.
*/
final String resultKey = resultState.getDocument().getName().split("-")[0];
result.putIfAbsent(resultKey, new HashSet<String>());
for (EntityAnnotation resultEntity : resultState.getEntities()) {
result.get(resultKey).add(new EntityDisambComparisonObject(resultEntity).toString());
}
/*
* Split to get on documents name level instead of the sentence level.
*/
final String goldKey = goldState.getDocument().getName().split("-")[0];
gold.putIfAbsent(goldKey, new HashSet<String>());
for (EntityAnnotation goldEntity : goldState.getEntities()) {
gold.get(goldKey).add(new EntityDisambComparisonObject(goldEntity).toString());
}
return PRF1Extended.objectiveFunction(gold, result);
}
示例9: checkTransportGroup
import java.util.Map; //导入方法依赖的package包/类
protected void checkTransportGroup(List<Transport> group) {
// order value must be different, otherwise, maybe will choose a random transport
Map<Integer, Transport> orderMap = new HashMap<>();
for (Transport transport : group) {
Transport existTransport = orderMap.putIfAbsent(transport.getOrder(), transport);
if (existTransport != null) {
throw new ServiceCombException(String.format("%s and %s have the same order %d",
existTransport.getClass().getName(),
transport.getClass().getName(),
transport.getOrder()));
}
}
}
示例10: canonicalizeLocal
import java.util.Map; //导入方法依赖的package包/类
private static DebugLocalInfo canonicalizeLocal(
LocalVariableNode node,
Map<DebugLocalInfo, DebugLocalInfo> canonicalLocalVariables,
JarApplicationReader application) {
DebugLocalInfo info = new DebugLocalInfo(
application.getString(node.name),
application.getTypeFromDescriptor(node.desc),
node.signature == null ? null : application.getString(node.signature));
DebugLocalInfo canonical = canonicalLocalVariables.putIfAbsent(info, info);
return canonical != null ? canonical : info;
}
示例11: groupByMutType
import java.util.Map; //导入方法依赖的package包/类
/**
* Filter mutations by gene then groups the result by their primary MutType.
*
* @param gene
* @return Map<MutType, MutationSet>
*/
public Map<MutType, MutationSet> groupByMutType(final Gene gene) {
Map<MutType, MutationSet> r = filterAndGroupBy(
mut -> mut.getGene() == gene,
mut -> mut.getPrimaryType());
List<MutType> mutTypes = gene.getMutationTypes();
if (r.size() < mutTypes.size()) {
for (MutType mt: mutTypes) {
r.putIfAbsent(mt, new MutationSet());
}
}
return r;
}
示例12: addSocketPermissionForTransportProfiles
import java.util.Map; //导入方法依赖的package包/类
/**
* Add dynamic {@link SocketPermission} based on transport settings. This method will first check if there is a port range specified in
* the transport profile specified by {@code profileSettings} and will fall back to {@code settings}.
*
* @param policy the {@link Permissions} instance to apply the dynamic {@link SocketPermission}s to
* @param settings the {@link Settings} instance to read the transport settings from
*/
private static void addSocketPermissionForTransportProfiles(
final Permissions policy,
final Settings settings) {
// transport is way over-engineered
final Map<String, Settings> profiles = new HashMap<>(TransportSettings.TRANSPORT_PROFILES_SETTING.get(settings).getAsGroups());
profiles.putIfAbsent(TransportSettings.DEFAULT_PROFILE, Settings.EMPTY);
// loop through all profiles and add permissions for each one, if it's valid; otherwise Netty transports are lenient and ignores it
for (final Map.Entry<String, Settings> entry : profiles.entrySet()) {
final Settings profileSettings = entry.getValue();
final String name = entry.getKey();
// a profile is only valid if it's the default profile, or if it has an actual name and specifies a port
// TODO: can this leniency be removed?
final boolean valid =
TransportSettings.DEFAULT_PROFILE.equals(name) ||
(name != null && name.length() > 0 && profileSettings.get("port") != null);
if (valid) {
final String transportRange = profileSettings.get("port");
if (transportRange != null) {
addSocketPermissionForPortRange(policy, transportRange);
} else {
addSocketPermissionForTransport(policy, settings);
}
}
}
}
示例13: listTableColumns
import java.util.Map; //导入方法依赖的package包/类
/**
* Gets the metadata for all columns that match the specified table prefix.
*
* @param session session
* @param prefix prefix
*/
@Override
public Map<SchemaTableName, List<ColumnMetadata>> listTableColumns(ConnectorSession session, SchemaTablePrefix prefix)
{
Map<SchemaTableName, List<ColumnMetadata>> tableColumns = new HashMap<>();
List<SchemaTableName> tableNames = metaDataQuery.listTables(prefix);
for (SchemaTableName table : tableNames) {
List<ColumnMetadata> columnMetadatas = metaDataQuery.getTableColMetadata(connectorId, table.getSchemaName(),
table.getTableName()).orElse(new ArrayList<>());
tableColumns.putIfAbsent(table, columnMetadatas);
}
return tableColumns;
}
示例14: add
import java.util.Map; //导入方法依赖的package包/类
boolean add(Binding binding) {
FieldValue selectorValue = binding.getArgument(Binding.JMS_SELECTOR_ARGUMENT);
Map<Queue, Binding> queueBindingMap;
if (selectorValue != null && !selectorValue.getValue().toString().isEmpty()) {
queueBindingMap = filteredQueueBindings;
} else {
queueBindingMap = unfilteredQueueBindings;
}
return queueBindingMap.putIfAbsent(binding.getQueue(), binding) == null;
}
示例15: putSingleHeader
import java.util.Map; //导入方法依赖的package包/类
private void putSingleHeader(String key, String value, Map<String, String> newHeaders) {
if (newHeaders.putIfAbsent(key, value) != null) {
throw new IllegalArgumentException("value for key [" + key + "] already present");
}
}