當前位置: 首頁>>代碼示例>>Java>>正文


Java Map.putIfAbsent方法代碼示例

本文整理匯總了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());
    }
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Cookbook,代碼行數:29,代碼來源:Chapter07Concurrency02.java

示例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();
}
 
開發者ID:ag-sc,項目名稱:JLink,代碼行數:21,代碼來源:CollectiveDictionary.java

示例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);
}
 
開發者ID:venus-boot,項目名稱:saluki,代碼行數:19,代碼來源:AbstractRegistry.java

示例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;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:27,代碼來源:CommonModuleUtils.java

示例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;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:32,代碼來源:Module.java

示例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);
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:21,代碼來源:VirtualPortCreateCommand.java

示例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());
  }
}
 
開發者ID:VerifAPS,項目名稱:stvs,代碼行數:33,代碼來源:Z3Solver.java

示例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);

}
 
開發者ID:ag-sc,項目名稱:JLink,代碼行數:27,代碼來源:ConceptObjectiveFunction.java

示例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()));
    }
  }
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:14,代碼來源:TransportManager.java

示例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;
}
 
開發者ID:inferjay,項目名稱:r8,代碼行數:12,代碼來源:JarSourceCode.java

示例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;
}
 
開發者ID:hivdb,項目名稱:sierra,代碼行數:19,代碼來源:MutationSet.java

示例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);
            }
        }
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:35,代碼來源:Security.java

示例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;
}
 
開發者ID:dbiir,項目名稱:paraflow,代碼行數:19,代碼來源:HDFSMetadata.java

示例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;
}
 
開發者ID:wso2,項目名稱:message-broker,代碼行數:11,代碼來源:BindingSet.java

示例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");
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:6,代碼來源:ThreadContext.java


注:本文中的java.util.Map.putIfAbsent方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。