Java Code Examples for java.util.Map.putIfAbsent()

The following are Jave code examples for showing how to use putIfAbsent() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Java-9-Cookbook   File: Chapter07Concurrency02.java   View Source Code Vote up 6 votes
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());
    }
}
 
Example 2
Project: JLink   File: CollectiveDictionary.java   View Source Code Vote up 6 votes
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();
}
 
Example 3
Project: saluki   File: AbstractRegistry.java   View Source Code Vote up 6 votes
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);
}
 
Example 4
Project: incubator-netbeans   File: CommonModuleUtils.java   View Source Code Vote up 6 votes
@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;
}
 
Example 5
Project: openjdk-jdk10   File: Module.java   View Source Code Vote up 6 votes
/**
 * 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;
}
 
Example 6
Project: athena   File: VirtualPortCreateCommand.java   View Source Code Vote up 6 votes
@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);
}
 
Example 7
Project: stvs   File: Z3Solver.java   View Source Code Vote up 6 votes
/**
 * 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());
  }
}
 
Example 8
Project: JLink   File: ConceptObjectiveFunction.java   View Source Code Vote up 6 votes
@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);

}
 
Example 9
Project: incubator-servicecomb-java-chassis   File: TransportManager.java   View Source Code Vote up 5 votes
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()));
    }
  }
}
 
Example 10
Project: r8   File: JarSourceCode.java   View Source Code Vote up 5 votes
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;
}
 
Example 11
Project: sierra   File: MutationSet.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 12
Project: elasticsearch_my   File: Security.java   View Source Code Vote up 5 votes
/**
 * 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);
            }
        }
    }
}
 
Example 13
Project: paraflow   File: HDFSMetadata.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 14
Project: message-broker   File: BindingSet.java   View Source Code Vote up 5 votes
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;
}
 
Example 15
Project: elasticsearch_my   File: ThreadContext.java   View Source Code Vote up 4 votes
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");
    }
}
 
Example 16
Project: ijcnlp2017-cmaps   File: SubgraphILPByComponent.java   View Source Code Vote up 4 votes
@Override
public Set<Concept> getSubgraph() {

	// build adjacency list
	Map<Concept, Set<Proposition>> propsByConcept = new HashMap<Concept, Set<Proposition>>();
	for (Proposition p : propositions) {
		propsByConcept.putIfAbsent(p.sourceConcept, new HashSet<Proposition>());
		propsByConcept.get(p.sourceConcept).add(p);
		propsByConcept.putIfAbsent(p.targetConcept, new HashSet<Proposition>());
		propsByConcept.get(p.targetConcept).add(p);
	}
	for (Concept c : concepts)
		propsByConcept.putIfAbsent(c, new HashSet<Proposition>());

	// find connected components
	List<Set<Concept>> components = ConnectedComponents.findConnectedComponents(concepts, propsByConcept);

	// check each component
	double bestScore = -Double.MAX_VALUE;
	Set<Concept> bestSubgraph = null;
	for (Set<Concept> component : components) {

		// if even the full component cannot be better, skip
		double maxScore = component.stream().mapToDouble(x -> x.weight).sum();
		if (maxScore <= bestScore)
			continue;

		double score;
		Set<Concept> subgraph = null;

		// if smaller than max -> already a solution
		if (component.size() <= this.maxSize) {

			score = maxScore;
			subgraph = component;

		} else {

			// if not, run ILP to find best subgraph
			Set<Proposition> compProps = component.stream().flatMap(x -> propsByConcept.get(x).stream())
					.collect(Collectors.toSet());
			SubgraphILPFast ilp = new SubgraphILPFast(new ArrayList<Concept>(component),
					new ArrayList<Proposition>(compProps), maxSize, maxTime);
			subgraph = ilp.getSubgraph();
			score = subgraph.stream().mapToDouble(x -> x.weight).sum();
		}

		if (score > bestScore) {
			bestScore = score;
			bestSubgraph = subgraph;
		}
	}

	return bestSubgraph;
}
 
Example 17
Project: argument-reasoning-comprehension-task   File: Step3cReasonGistExporter.java   View Source Code Vote up 4 votes
public static void exportReasonGist(File inputFile, File outputCSVFile)
        throws Exception
{
    List<StandaloneArgument> arguments = XStreamSerializer
            .deserializeArgumentListFromXML(inputFile);

    // result: stance; reasonid; gist

    Map<String, Map<String, String>> reasonIdGistMap = new TreeMap<>();

    for (StandaloneArgument standaloneArgument : arguments) {
        List<StandaloneArgumentWithSinglePremise> argumentWithSinglePremises = StandaloneArgumentWithSinglePremise
                .extractPremises(standaloneArgument);

        for (StandaloneArgumentWithSinglePremise standaloneArgumentWithSinglePremise : argumentWithSinglePremises) {
            // stance
            String stance = standaloneArgumentWithSinglePremise.getAnnotatedStance();

            String gist = standaloneArgumentWithSinglePremise.getPremise().getGist();
            String reasonId = standaloneArgumentWithSinglePremise.getPremise().getPremiseId();

            DisambiguatedStance disambiguatedStance = null;
            String disambiguatedStanceString = standaloneArgumentWithSinglePremise.getPremise()
                    .getDisambiguatedStance();
            if (disambiguatedStanceString != null) {
                disambiguatedStance = DisambiguatedStance.valueOf(disambiguatedStanceString);
            }

            // we want only clear stance-taking reason
            if (gist != null && DisambiguatedStance.ORIGINAL.equals(disambiguatedStance)) {
                reasonIdGistMap.putIfAbsent(stance, new TreeMap<>());
                reasonIdGistMap.get(stance).put(reasonId, gist);
            }
        }
    }

    // save to a tab-separated file
    PrintWriter pw = new PrintWriter(outputCSVFile);
    reasonIdGistMap.forEach((stance, reasonIdsGist) -> reasonIdsGist.forEach(
            (reasonId, gist) -> pw.println(stance + "\t" + reasonId + "\t" + gist))
    );
    IOUtils.closeQuietly(pw);
}
 
Example 18
Project: JLink   File: DataReader.java   View Source Code Vote up 4 votes
public static Map<String, Set<String>> getDiseaseChemicalSurfaceFormToIDMapping(final EDataset dataset)
		throws IOException {

	Map<String, Set<String>> ids = new HashMap<String, Set<String>>();
	final String inputFileName;

	inputFileName = getInputFileName(dataset);

	BufferedReader br = new BufferedReader(new FileReader(new File(inputFileName)));
	ECorpus corpus = JLink.setting.corpus;

	String line = "";
	while ((line = br.readLine()) != null) {
		if (line.trim().isEmpty() || line.startsWith("#"))
			continue;

		/*
		 * Filter abstract lines and store them.
		 */
		if (line.matches("[0-9]+\\|[ta]\\|.*")) {
			continue;
		} else {
			final String[] data = line.split(SEPERATOR);

			if (data.length < 6)
				continue;

			String id = data[INDEX_DISEASE_ID].trim();
			String sf = data[INDEX_DISEASE_SURFACEFORM].trim();

			if ((corpus == ECorpus.BC5) && id.equals("MESH:-1"))
				continue;
			/*
			 * Split id at '+'-sign and assign both ids in separate to the
			 * specific disease surface form.
			 */
			for (String partID : id.split("\\+")) {
				partID = buildDiseaseID(partID);

				ids.putIfAbsent(partID, new HashSet<String>());

				ids.get(partID).add(sf);
			}
		}
	}
	br.close();
	return ids;
}
 
Example 19
Project: JLink   File: PRF1Extended.java   View Source Code Vote up 4 votes
public static void calculate(Map<String, Set<String>> goldData, Map<String, Set<String>> baselineData,
		boolean print) {

	for (String abstarctID : goldData.keySet()) {
		baselineData.putIfAbsent(abstarctID, new HashSet<String>());
	}

	int tp = 0;
	int fp = 0;
	int fn = 0;
	double macroPrecision = 0;
	double macroRecall = 0;
	double macroF1 = 0;
	for (String pubmedID : goldData.keySet()) {

		tp += getTruePositives(goldData.get(pubmedID), baselineData.get(pubmedID));

		fp += getFalsePositives(goldData.get(pubmedID), baselineData.get(pubmedID));

		fn += getFalseNegatives(goldData.get(pubmedID), baselineData.get(pubmedID));

		macroPrecision += macroPrecision(goldData.get(pubmedID), baselineData.get(pubmedID));
		macroRecall += macroRecall(goldData.get(pubmedID), baselineData.get(pubmedID));
		// macroF1 += macroF1(goldData.get(pubmedID),
		// baselineData.get(pubmedID));
	}

	macroPrecision /= goldData.size();
	macroRecall /= goldData.size();
	// macroF1 /= goldData.size();
	// NCBI_DiseaseLearning.log.info("REAL = " + macroF1);
	macroF1 = macroF1(macroPrecision, macroRecall);
	// System.out.println("REAL = " + macroF1(macroPrecision, macroRecall));

	JLink.log.info("tp = " + round(tp));
	JLink.log.info("fp = " + round(fp));
	JLink.log.info("fn = " + round(fn));
	JLink.log.info("Micro precision = " + round(microPrecision(tp, fp, fn)));
	JLink.log.info("Micro recall = " + round(microRecall(tp, fp, fn)));
	JLink.log.info("Micro F1 = " + round(microF1(tp, fp, fn)));
	JLink.log.info("");
	JLink.log.info("Macro precision = " + round(macroPrecision));
	JLink.log.info("Macro recall = " + round(macroRecall));
	JLink.log.info("Macro F1 = " + round(macroF1));
	JLink.log.info("");

	if (print)
		JLink.results.print((round(microF1(tp, fp, fn))) + "\t" + round(microPrecision(tp, fp, fn)) + "\t"
				+ round(microRecall(tp, fp, fn)) + "\t" + round(macroF1) + "\t" + round(macroPrecision) + "\t"
				+ round(macroRecall) + "\t" + round(tp) + "\t" + round(fp) + "\t" + round(fn) + "\t");
}
 
Example 20
Project: JLink   File: IDFDictionaryCheck.java   View Source Code Vote up 2 votes
public static void main(String[] args) throws IOException {

		lemmatizer = new StanfordLemmatizer();

		dict = (DiseaseDictionary) restoreData("gen/medic_train_lemmatized_tokenized_dict.bin");

		if (dict == null) {
			dict = DiseaseDictionaryFactory.getInstance(true, ETokenizationType.SIMPLE, true, true, false, false);
			writeData("gen/medic_train_lemmatized_tokenized_dict.bin", dict);
		}

		File termRationFile = new File("gen/medline_bigram_term_ratio.csv");

		termRatio = readTermRatioFromFile(termRationFile);

		idf = (Map<String, Double>) restoreData("gen/bigram_dictionary_idf.sdhm");
		if (idf == null) {
			Map<String, List<String>> documents = new HashMap<>();

			for (Entry<MEDICDisease, Set<String>> dictEntry : dict.getDictionary().entrySet()) {

				documents.putIfAbsent(dictEntry.getKey().diseaseID, new ArrayList<>());

				documents.get(dictEntry.getKey().diseaseID)
						.addAll(getNTuples(dictEntry.getKey().normalizedForm, N_GRAM_SIZE));

				documents.get(dictEntry.getKey().diseaseID).addAll(dictEntry.getValue().stream()
						.flatMap(e -> getNTuples(e, N_GRAM_SIZE).stream()).collect(Collectors.toList()));

			}

			idf = TFIDF.getIDFs(documents);

			writeData("gen/bigram_dictionary_idf.sdhm", idf);
		}

		maxIDF = idf.values().stream().max(Double::compareTo).get();

		// getBestDictEntries("autosomal dominant multisystem
		// disorder").forEach(System.out::println);
		// getBestDictEntries("atrophic benign epidermolysis
		// bullosa").forEach(System.out::println);

	}