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

The following are Jave code examples for showing how to use containsKey() 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: elasticsearch_my   File: AsyncShardFetch.java   View Source Code Vote up 6 votes
/**
 * Fills the shard fetched data with new (data) nodes and a fresh NodeEntry, and removes from
 * it nodes that are no longer part of the state.
 */
private void fillShardCacheWithDataNodes(Map<String, NodeEntry<T>> shardCache, DiscoveryNodes nodes) {
    // verify that all current data nodes are there
    for (ObjectObjectCursor<String, DiscoveryNode> cursor : nodes.getDataNodes()) {
        DiscoveryNode node = cursor.value;
        if (shardCache.containsKey(node.getId()) == false) {
            shardCache.put(node.getId(), new NodeEntry<T>(node.getId()));
        }
    }
    // remove nodes that are not longer part of the data nodes set
    for (Iterator<String> it = shardCache.keySet().iterator(); it.hasNext(); ) {
        String nodeId = it.next();
        if (nodes.nodeExists(nodeId) == false) {
            it.remove();
        }
    }
}
 
Example 2
Project: sstore-soft   File: Maps.java   View Source Code Vote up 6 votes
private static <K, V> void doDifference(
    Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right,
    Equivalence<? super V> valueEquivalence,
    Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth,
    Map<K, MapDifference.ValueDifference<V>> differences) {
  for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
    K leftKey = entry.getKey();
    V leftValue = entry.getValue();
    if (right.containsKey(leftKey)) {
      V rightValue = onlyOnRight.remove(leftKey);
      if (valueEquivalence.equivalent(leftValue, rightValue)) {
        onBoth.put(leftKey, leftValue);
      } else {
        differences.put(
            leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
      }
    } else {
      onlyOnLeft.put(leftKey, leftValue);
    }
  }
}
 
Example 3
Project: incubator-netbeans   File: AnalyserAnalyser.java   View Source Code Vote up 6 votes
private static void p (Map m, String i, PrintWriter writer, Language language) {
    Iterator it = m.keySet ().iterator ();
    while (it.hasNext ()) {
        Object e = it.next ();
        if ("&".equals (e)) continue;
        if ("#".equals (e)) continue;
        if ("*".equals (e)) continue;
        T t = (T) e;
        Map m1 = (Map) m.get (e);
        String s = m1.containsKey ("#") ? ("#" + m1.get ("#").toString ()) : "";
        if (writer == null)
            System.out.println (i + t.toString (language) + " " + m1.get ("&") + " " + s);
        else
            writer.println (i + t.toString (language) + " " + m1.get ("&") + " " + s);
        p (m1, i + "  ", writer, language);
    }
}
 
Example 4
Project: sierra   File: TabularResistanceSummary.java   View Source Code Vote up 6 votes
private static List<String> getScoredMutationsIN(Map<Gene, GeneDR> resistanceResults) {
	List<String> scoredMutations = new ArrayList<>();
	String inMajor = "NA";
	String inAccessory = "NA";
	if (resistanceResults.containsKey(Gene.IN)) {
		GeneDR inResults = resistanceResults.get(Gene.IN);
		if (inResults.groupMutationsByTypes().containsKey(MutType.Major)) {
			MutationSet major = inResults.groupMutationsByTypes().get(MutType.Major);
			inMajor = major.join();
		} else {
			inMajor = "None";
		}
		if (inResults.groupMutationsByTypes().containsKey(MutType.Accessory)) {
			MutationSet accessory = inResults.groupMutationsByTypes().get(MutType.Accessory);
			inAccessory = accessory.join();
		} else {
			inAccessory = "None";
		}
	}
	scoredMutations.add(inMajor);
	scoredMutations.add(inAccessory);
	return scoredMutations;
}
 
Example 5
Project: BecomeJavaHero   File: Reader2.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
	Scanner scanner = new Scanner(System.in);
	Map<Character, Integer> counter = new HashMap<>();
	
	String line = scanner.nextLine();
	
	for (int i = 0; i < line.length(); i++) {
		char a = line.charAt(i);
		if (counter.containsKey(a)) {
			int w = counter.get(a);
			counter.put(a, w+1);
		} else {
			counter.put(a, 1);
		}
	}
	
	for (Entry<Character, Integer> entry : counter.entrySet()) {
		System.out.println(entry.getKey() + " => " + entry.getValue());
	}
	
}
 
Example 6
Project: Backmemed   File: ModelAdapterHorse.java   View Source Code Vote up 6 votes
public ModelRenderer getModelRenderer(ModelBase model, String modelPart)
{
    if (!(model instanceof ModelHorse))
    {
        return null;
    }
    else
    {
        ModelHorse modelhorse = (ModelHorse)model;
        Map<String, Integer> map = getMapPartFields();

        if (map.containsKey(modelPart))
        {
            int i = ((Integer)map.get(modelPart)).intValue();
            return (ModelRenderer)Reflector.getFieldValue(modelhorse, Reflector.ModelHorse_ModelRenderers, i);
        }
        else
        {
            return null;
        }
    }
}
 
Example 7
Project: Java-EX   File: CacheUtil.java   View Source Code Vote up 5 votes
public static <V> Optional<V> get(Object owner, Object key) {
  Map<Object, Object> map = getMap(owner);
  if (map.containsKey(key)) {
    return Optional.of((V) map.get(key));
  }
  return Optional.empty();
}
 
Example 8
Project: openjdk-jdk10   File: ParserImpl.java   View Source Code Vote up 5 votes
private CompilationUnitTree parseModule(final ScriptObjectMirror scriptObj, final DiagnosticListener listener) throws NashornException {
    final Map<?, ?> map = Objects.requireNonNull(scriptObj);
    if (map.containsKey("script") && map.containsKey("name")) {
        final String script = JSType.toString(map.get("script"));
        final String name = JSType.toString(map.get("name"));
        final Source src = Source.sourceFor(name, script);
        return makeModule(src, listener);
    } else {
        throw new IllegalArgumentException("can't find 'script' and 'name' properties");
    }
}
 
Example 9
Project: Reer   File: DefaultSourceDirectorySet.java   View Source Code Vote up 5 votes
public Set<DirectoryTree> getSrcDirTrees() {
    // This implementation is broken. It does not consider include and exclude patterns
    Map<File, DirectoryTree> trees = new LinkedHashMap<File, DirectoryTree>();
    for (DirectoryTree tree : doGetSrcDirTrees()) {
        if (!trees.containsKey(tree.getDir())) {
            trees.put(tree.getDir(), tree);
        }
    }
    return new LinkedHashSet<DirectoryTree>(trees.values());
}
 
Example 10
Project: Excel2XML   File: E2xCmdline.java   View Source Code Vote up 5 votes
/**
 * Writes out an XML cell based on coordinates and provided value
 * 
 * @param row
 *            the row index of the cell
 * @param col
 *            the column index
 * @param cellValue
 *            value of the cell, can be null for an empty cell
 * @param out
 *            the XML output stream
 * @param columns
 *            the Map with column titles
 */
private void writeAnyCell(final int row, final int col, final String cellValue, final XMLStreamWriter out,
		final Map<String, String> columns) {
	try {
		out.writeStartElement("cell");
		String colNum = String.valueOf(col);
		out.writeAttribute("row", String.valueOf(row));
		out.writeAttribute("col", colNum);
		if (columns.containsKey(colNum)) {
			out.writeAttribute("title", columns.get(colNum));
		}
		if (cellValue != null) {
			if (cellValue.contains("<") || cellValue.contains(">")) {
				out.writeCData(cellValue);
			} else {
				out.writeCharacters(cellValue);
			}
		} else {
			out.writeAttribute("empty", "true");
		}
		out.writeEndElement();

	} catch (XMLStreamException e) {
		e.printStackTrace();
	}

}
 
Example 11
Project: plugin-redirect   File: RedirectResource.java   View Source Code Vote up 5 votes
/**
 * Check the hash for the given user against the stored value from the data
 * base.
 */
private String checkUrl(final String user, final String hashData, final Map<String, Object> settings) {
	if (settings.containsKey(PREFERRED_HASH)) {
		// User has selected a preferred URL, check the corresponding hash
		if (hashData.equals(settings.get(PREFERRED_HASH))) {
			// Hash matches, return the URL
			return (String) settings.get(PREFERRED_URL);
		}

		// Attempt or bug? report it.
		log.error("Attempt to access preferred URL with cookie value : {}|{}", user, hashData);
	}
	return null;
}
 
Example 12
Project: elasticsearch-linear-regression   File: PredictionAggregationParser.java   View Source Code Vote up 5 votes
@Override
protected PredictionAggregationBuilder createInnerFactory(final String aggregationName,
    final Map<ParseField, Object> otherOptions) {
  final PredictionAggregationBuilder builder = new PredictionAggregationBuilder(aggregationName);
  if (otherOptions.containsKey(INPUTS)) {
    final List<Double> inputsList = (List<Double>) otherOptions.get(INPUTS);
    final double[] inputs = new double[inputsList.size()];
    int i = 0;
    for (final Double input : inputsList) {
      inputs[i++] = input;
    }
    builder.inputs(inputs);
  }
  return builder;
}
 
Example 13
Project: alvisnlp   File: AlvisIRIndexer.java   View Source Code Vote up 5 votes
private static Map<String,Integer> getNamesIndex(String[] names) {
	Map<String,Integer> result = new LinkedHashMap<String,Integer>();
	for (String s : names) {
		if (!result.containsKey(s)) {
			result.put(s, result.size());
		}
	}
	return result;		
}
 
Example 14
Project: openjdk-jdk10   File: Canonicalizer20010315.java   View Source Code Vote up 5 votes
void getXmlnsAttr(Collection<Attr> col) {
    int size = levels.size() - 1;
    if (cur == null) {
        cur = new XmlsStackElement();
        cur.level = currentLevel;
        lastlevel = currentLevel;
        levels.add(cur);
    }
    boolean parentRendered = false;
    XmlsStackElement e = null;
    if (size == -1) {
        parentRendered = true;
    } else {
        e = levels.get(size);
        if (e.rendered && e.level + 1 == currentLevel) {
            parentRendered = true;
        }
    }
    if (parentRendered) {
        col.addAll(cur.nodes);
        cur.rendered = true;
        return;
    }

    Map<String, Attr> loa = new HashMap<String, Attr>();
    for (; size >= 0; size--) {
        e = levels.get(size);
        Iterator<Attr> it = e.nodes.iterator();
        while (it.hasNext()) {
            Attr n = it.next();
            if (!loa.containsKey(n.getName())) {
                loa.put(n.getName(), n);
            }
        }
    }

    cur.rendered = true;
    col.addAll(loa.values());
}
 
Example 15
Project: sshd-shell-spring-boot   File: BaseUserInputProcessor.java   View Source Code Vote up 5 votes
private String handleUserInputWithMoreTokens(String[] part, Collection<String> userRoles) throws
        InterruptedException, ShellException {
    Map<String, CommandExecutableDetails> commandExecutables = commandMap.get(part[0]);
    if (!commandExecutables.containsKey(part[1])) {
        throw new ShellException("Unknown subcommand '" + part[1] + "'. Type '" + part[0]
                + "' for supported subcommands");
    }
    CommandExecutableDetails ced = commandMap.get(part[0]).get(part[1]);
    validateExecutableWithUserRole(ced, userRoles);
    return ced.executeWithArg(part.length == 2 ? null : part[2]);
}
 
Example 16
Project: uavstack   File: HttpMessage.java   View Source Code Vote up 5 votes
protected Map<String, List<String>> parseQueryString(String s) {

        Map<String, List<String>> map = new HashMap<String, List<String>>();
        if (s == null) {
            return map;
        }

        List<String> vals = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(s, "&");
        while (st.hasMoreTokens()) {
            String pair = st.nextToken();
            int pos = pair.indexOf('=');
            if (pos == -1) {
                throw new IllegalArgumentException();
            }
            String key = pair.substring(0, pos);
            String val = pair.substring(pos + 1, pair.length());
            if (map.containsKey(key)) {
                List<String> oldVals = map.get(key);
                // vals = new String[oldVals.length + 1];
                for (int i = 0; i < oldVals.size(); i++) {
                    vals.add(oldVals.get(i));
                }
                vals.add(val);
            }
            else {
                vals.add(val);
            }
            map.put(key, vals);
        }
        return map;
    }
 
Example 17
Project: Spring-Security-Third-Edition   File: JpaMutableAclService.java   View Source Code Vote up 5 votes
@Override
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException {
    Map<ObjectIdentity, Acl> result = lookupStrategy.readAclsById(objects, sids);

    // Check every requested object identity was found (throw NotFoundException if needed)
    for (ObjectIdentity oid : objects) {
        if (!result.containsKey(oid)) {
            throw new NotFoundException("Unable to find ACL information for object identity '" + oid + "'");
        }
    }

    return result;
}
 
Example 18
Project: incubator-netbeans   File: Evaluator.java   View Source Code Vote up 5 votes
/**
 * Gives a map from test type (e.g. <em>unit</em> or <em>qa-functional</em>)
 * to the {@link TestClasspath test classpath} according to the content in
 * the project's metadata (<em>project.xml<em>).
 */
private Map<String,TestClasspath> computeTestingClassPaths(ModuleList ml, PropertyEvaluator evaluator, Set<String> extraTestTypes) {
    Map<String, TestClasspath> classpaths = new HashMap<String,TestClasspath>();
    ProjectXMLManager pxm = new ProjectXMLManager(project);
    Map<String, Set<TestModuleDependency>> testDependencies = pxm.getTestDependencies(ml);
    
    String testDistDir =  evaluator.getProperty("test.dist.dir"); // NOI18N
    if (testDistDir == null) {
        NbModuleType type = project.getModuleType();
        if (type == NbModuleType.NETBEANS_ORG) {
            // test.dist.dir = ${nb_all}/nbbuild/build/testdist
            String nball = evaluator.getProperty("nb_all"); // NOI18N
            testDistDir = nball + File.separatorChar + "nbbuild" + File.separatorChar + "build" + File.separatorChar + "testdist"; // NOI18N
        } else if ( type == NbModuleType.SUITE_COMPONENT) {
            // test.dist.dir = ${suite.build.dir}/testdist
            String suiteDir = evaluator.getProperty("suite.build.dir"); // NOI18N
            testDistDir = suiteDir + File.separatorChar + "testdist"; // NOI18N
        } else {
            // standalone module
            // test.dist.dir = ${build.dir}/testdist
            String moduleDir = evaluator.getProperty("build.dir"); // NOI18N
            testDistDir = moduleDir + File.separatorChar + "testdist"; // NOI18N
        }
    }
    for (Map.Entry<String,Set<TestModuleDependency>> entry : testDependencies.entrySet()) {
        computeTestType(entry.getKey(), new File(testDistDir), entry.getValue(), classpaths, ml);
    }
    for (String testType : extraTestTypes) {
        if (!testDependencies.containsKey(testType)) {
            // No declared dependencies of this type, so will definitely need to add in compatibility libraries.
            computeTestType(testType, new File(testDistDir), Collections.<TestModuleDependency>emptySet(), classpaths, ml);
        }
    }
    return classpaths;
}
 
Example 19
Project: alfresco-repository   File: VersionableAspect.java   View Source Code Vote up 4 votes
/**
 * On update properties policy behaviour 
 * 
 * If applicable and "cm:autoVersionOnUpdateProps" is TRUE then version the node on properties update (even if no content updates)
 * 
 * @since 3.2
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void onUpdateProperties(
        NodeRef nodeRef,
        Map<QName, Serializable> before,
        Map<QName, Serializable> after)
{
    if ((this.nodeService.exists(nodeRef) == true) &&
        !lockService.isLockedAndReadOnly(nodeRef) &&
        (this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE) == true) && 
        (this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPORARY) == false))
    {
        onUpdatePropertiesBehaviour.disable();
        try
        {
            Map<NodeRef, NodeRef> versionedNodeRefs = (Map)AlfrescoTransactionSupport.getResource(KEY_VERSIONED_NODEREFS);
            if (versionedNodeRefs == null || versionedNodeRefs.containsKey(nodeRef) == false)
            {
                boolean autoVersionProps = false;
                Boolean value = (Boolean)this.nodeService.getProperty(nodeRef, ContentModel.PROP_AUTO_VERSION_PROPS);
                if (value != null)
                {
                    // If the value is not null then 
                    autoVersionProps = value.booleanValue();
                }
                
                if (autoVersionProps == true)
                {
                    // Check for explicitly excluded props - if one or more excluded props changes then do not auto-version on this event (even if other props changed)
                    if (excludedOnUpdatePropQNames.size() > 0)
                    {
                        Set<QName> propNames = new HashSet<QName>(after.size() * 2);
                        propNames.addAll(after.keySet());
                        propNames.addAll(before.keySet());
                        propNames.retainAll(excludedOnUpdatePropQNames);

                        if (propNames.size() > 0)
                        {
                            for (QName prop : propNames)
                            {
                                Serializable beforeValue = before.get(prop);
                                Serializable afterValue = after.get(prop);
                                
                                if (EqualsHelper.nullSafeEquals(beforeValue, afterValue) != true)
                                {
                                    // excluded - do not version
                                    return;
                                }
                            }
                        }
                        
                        // drop through and auto-version
                    }
                    
                    // Create the auto-version
                    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>(4);
                    versionProperties.put(Version.PROP_DESCRIPTION, I18NUtil.getMessage(MSG_AUTO_VERSION_PROPS));
                    versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
                    
                    createVersionImpl(nodeRef, versionProperties);
                }
            }
        }
        finally
        {
            onUpdatePropertiesBehaviour.enable();
        }
    }
}
 
Example 20
Project: Proyecto-DASI   File: ClientStateMachine.java   View Source Code Vote up 4 votes
@Override
public void onMessage(MalmoMessageType messageType, Map<String, String> data)
{
    super.onMessage(messageType, data);
    // This message will be sent to us once the server has decided the mission is over.
    if (messageType == MalmoMessageType.SERVER_STOPAGENTS)
    {
        this.quitCode = data.containsKey("QuitCode") ? data.get("QuitCode") : "";
        try
        {
            // Save the quit code for anything that needs it:
            MalmoMod.getPropertiesForCurrentThread().put("QuitCode", this.quitCode);
        }
        catch (Exception e)
        {
            System.out.println("Failed to get properties - final reward may go missing.");
        }
        // Get the final reward data:
        ClientAgentConnection cac = currentMissionInit().getClientAgentConnection();
        if (currentMissionBehaviour() != null && currentMissionBehaviour().rewardProducer != null && cac != null)
            currentMissionBehaviour().rewardProducer.getReward(currentMissionInit(), ClientStateMachine.this.finalReward);

        onMissionEnded(ClientState.MISSION_ENDED, null);
    }
    else if (messageType == MalmoMessageType.SERVER_GO)
    {
        // First, force all entities to get re-added to their chunks, clearing out any old entities in the process.
        // We need to do this because the process of teleporting all agents to their start positions, combined
        // with setting them to/from spectator mode, leaves the client chunk entity lists etc in a parlous state.
        List lel = Minecraft.getMinecraft().theWorld.loadedEntityList;
        for (int i = 0; i < lel.size(); i++)
        {
            Entity entity = (Entity)lel.get(i);
            Chunk chunk = Minecraft.getMinecraft().theWorld.getChunkFromChunkCoords(entity.chunkCoordX, entity.chunkCoordZ);
            List<Entity> entitiesToRemove = new ArrayList<Entity>();
            for (int k = 0; k < chunk.getEntityLists().length; k++)
            {
                Iterator iterator = chunk.getEntityLists()[k].iterator();
                while (iterator.hasNext())
                {
                    Entity chunkent = (Entity)iterator.next();
                    if (chunkent.getEntityId() == entity.getEntityId())
                    {
                        entitiesToRemove.add(chunkent);
                    }
                }
            }
            for (Entity removeEnt : entitiesToRemove)
            {
                chunk.removeEntity(removeEnt);
            }
            entity.addedToChunk = false;    // Will force it to get re-added to the chunk list.
        }
        this.serverHasFiredStartingPistol = true; // GO GO GO!
    }
}