java.util.HashMap#containsKey ( )源码实例Demo

下面列出了java.util.HashMap#containsKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Hackerrank-Solutions   文件: DPCoinChange.java
private static long makeChange(int[] coins, int money, int index, HashMap<String, Long> memo) {
	if (money == 0)
		return 1;
	if (index >= coins.length)
		return 0;

	String key = money + "-" + index;
	if (memo.containsKey(key)) {
		return memo.get(key);
	}

	int amountWithCoin = 0;
	long ways = 0;
	while (amountWithCoin <= money) {
		int remaining = money - amountWithCoin;
		ways += makeChange(coins, remaining, index + 1, memo);
		amountWithCoin += coins[index];
	}
	memo.put(key, ways);
	return ways;
}
 
源代码2 项目: systemds   文件: RemoteParForUtils.java
public static LocalVariableMap[] getResults(List<Tuple2<Long,String>> out, Log LOG )
{
	HashMap<Long,LocalVariableMap> tmp = new HashMap<>();
	
	int countAll = 0;
	for( Tuple2<Long,String> entry : out ) {
		Long key = entry._1();
		String val = entry._2();
		if( !tmp.containsKey( key ) )
			tmp.put(key, new LocalVariableMap());
		Object[] dat = ProgramConverter.parseDataObject( val );
		tmp.get(key).put((String)dat[0], (Data)dat[1]);
		countAll++;
	}
	
	if( LOG != null ) {
		LOG.debug("Num remote worker results (before deduplication): "+countAll);
		LOG.debug("Num remote worker results: "+tmp.size());
	}
	
	//create return array
	return tmp.values().toArray(new LocalVariableMap[0]);
}
 
源代码3 项目: commcare-android   文件: EntityKeyFilterer.java
@Override
protected void filter() {
    if (isCancelled() || orderedKeySet.isEmpty()) {
        return;
    }

    // Add entities whose extra keys are in the key set, preserving key set
    // ordering. Don't assume one-to-one correspondence between entities
    // and keys: depending on the appliciation we might want to attach the
    // same data to multiple entities
    HashMap<String, List<Entity<TreeReference>>> keyToEntitiesMap =
            buildKeyToEntitiesMap(fullEntityList);
    for (String key : orderedKeySet) {
        if (keyToEntitiesMap.containsKey(key)) {
            matchList.addAll(keyToEntitiesMap.get(key));
        }
    }
}
 
源代码4 项目: codekata   文件: Solution.java
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    if (node == null) return null;

    HashMap<Integer, UndirectedGraphNode> map = new HashMap<>();
    map.put(node.label, new UndirectedGraphNode(node.label));

    Queue<UndirectedGraphNode> queue = new LinkedList<>();
    queue.add(node);

    while (queue.size() != 0) {
        UndirectedGraphNode origin = queue.poll(), next = map.get(origin.label);
        for (UndirectedGraphNode tmp : origin.neighbors) {
            if (!map.containsKey(tmp.label)) {
                map.put(tmp.label, new UndirectedGraphNode(tmp.label));
                queue.add(tmp);
            }
            next.neighbors.add(map.get(tmp.label));
        }
    }

    return map.get(node.label);
}
 
源代码5 项目: ha-bridge   文件: HueMulator.java
private Boolean filterByRequester(String requesterFilterList, String anAddress) {
	if (requesterFilterList == null || requesterFilterList.length() == 0)
		return true;

	HashMap<String, String> addressMap;
	addressMap = new HashMap<String, String>();
	if (requesterFilterList.contains(",")) {
		String[] theArray = requesterFilterList.split(",");
		for (String v : theArray) {
			addressMap.put(v.trim(), v.trim());
		}
	} else
		addressMap.put(requesterFilterList.trim(), requesterFilterList.trim());
	if (addressMap.containsKey(anAddress))
		return true;
	return false;
}
 
源代码6 项目: CloverETL-Engine   文件: StringUtils.java
public static CharSequence translateMapSearch(CharSequence in, CharSequence searchSet, CharSequence replaceSet) {
	HashMap<Character, Character> replacement = new HashMap<Character, Character>(searchSet.length());
	int replaceSetLength = replaceSet.length();
	for (int i = 0; i < searchSet.length(); i++) {
		replacement.put(searchSet.charAt(i), i < replaceSetLength ? replaceSet.charAt(i) : null);
	}
	StringBuilder result = new StringBuilder();
	Character r;
	char ch;
	for (int i = 0; i < in.length(); i++) {
		ch = in.charAt(i);
		if (replacement.containsKey(ch)) {
			if ((r = replacement.get(ch)) != null) {
				result.append(r);
			}
		} else {
			result.append(ch);
		}
	}
	return result.toString();
}
 
源代码7 项目: owt-client-android   文件: ConferenceAction.java
public static void applyOption(Subscription subscription, HashMap<String, String> videoParams,
        boolean expectation) {
    Subscription.VideoUpdateOptions videoUpdateOptions = new Subscription.VideoUpdateOptions();
    if (videoParams != null) {
        if (videoParams.containsKey("bitrateMultiplier")) {
            videoUpdateOptions.bitrateMultiplier = Double.parseDouble(
                    videoParams.get("bitrateMultiplier"));
        }
        if (videoParams.containsKey("frameRate")) {
            videoUpdateOptions.fps = Integer.valueOf(videoParams.get("frameRate"));
        }
        if (videoParams.containsKey("width")) {
            videoUpdateOptions.resolutionWidth = Integer.valueOf(videoParams.get("width"));
        }
        if (videoParams.containsKey("height")) {
            videoUpdateOptions.resolutionHeight = Integer.valueOf(videoParams.get("height"));
        }
        if (videoParams.containsKey("keyFrameInterval")) {
            videoUpdateOptions.keyframeInterval = Integer.valueOf(
                    videoParams.get("keyFrameInterval"));
        }
    }
    TestCallback<Void> callback = new TestCallback<>();
    subscription.applyOptions(videoUpdateOptions, callback);
    assertTrue(callback.getResult(expectation, TIMEOUT));
}
 
源代码8 项目: beakerx   文件: Inspect.java
private InspectResult getInspectResult(int caretPosition, String methodName, String className, String everything) {
    HashMap<String, ClassInspect> stringClassInspectHashMap = new SerializeInspect().fromJson(everything);
    InspectResult inspectResult = new InspectResult();
    ClassInspect classInspect = null;
    if (stringClassInspectHashMap.containsKey(className)) {
        classInspect = stringClassInspectHashMap.get(className);
    } else {
        for (ClassInspect cls : stringClassInspectHashMap.values()) {
            if (cls.getClassName().equals(className)) {
                classInspect = cls;
                break;
            }
        }
    }
    if (methodName == null && classInspect != null) {
        List<MethodInspect> constructors = classInspect.getConstructors();
        String classInfo = parseClassInfo(classInspect) + "\n\n" + parseMethodsInfo(constructors, "");
        inspectResult = new InspectResult(classInfo, caretPosition);
    } else {
        List<MethodInspect> methodInspectsList = classInspect == null ? null : classInspect.getMethods();
        if (methodInspectsList == null) {
            return new InspectResult();
        }
        List<MethodInspect> methods = methodInspectsList.stream()
                .filter(m -> m.getMethodName().equals(methodName))
                .collect(Collectors.toList());
        if (!methods.isEmpty()) {
            return new InspectResult(parseMethodsInfo(methods, className), caretPosition);
        }
    }
    return inspectResult;
}
 
源代码9 项目: ctsms   文件: VOCacheContext.java
public boolean voMapContainsKey(Class entityClass, Class voClass, Long id) {
	if (!getEntityIgnoreSet().contains(entityClass) && getEntityVoMap().containsKey(entityClass)) {
		HashMap<Long, HashMap<Class, Object>> voMap = getEntityVoMap().get(entityClass);
		if (voMap.containsKey(id)) {
			return voMap.get(id).containsKey(voClass);
		}
	}
	return false;
}
 
源代码10 项目: hadoop   文件: DFSAdmin.java
/**
 * Display each rack and the nodes assigned to that rack, as determined
 * by the NameNode, in a hierarchical manner.  The nodes and racks are
 * sorted alphabetically.
 * 
 * @throws IOException If an error while getting datanode report
 */
public int printTopology() throws IOException {
    DistributedFileSystem dfs = getDFS();
    final DatanodeInfo[] report = dfs.getDataNodeStats();

    // Build a map of rack -> nodes from the datanode report
    HashMap<String, TreeSet<String> > tree = new HashMap<String, TreeSet<String>>();
    for(DatanodeInfo dni : report) {
      String location = dni.getNetworkLocation();
      String name = dni.getName();
      
      if(!tree.containsKey(location)) {
        tree.put(location, new TreeSet<String>());
      }
      
      tree.get(location).add(name);
    }
    
    // Sort the racks (and nodes) alphabetically, display in order
    ArrayList<String> racks = new ArrayList<String>(tree.keySet());
    Collections.sort(racks);
    
    for(String r : racks) {
      System.out.println("Rack: " + r);
      TreeSet<String> nodes = tree.get(r);

      for(String n : nodes) {
        System.out.print("   " + n);
        String hostname = NetUtils.getHostNameOfIP(n);
        if(hostname != null)
          System.out.print(" (" + hostname + ")");
        System.out.println();
      }

      System.out.println();
    }
  return 0;
}
 
源代码11 项目: commcare-android   文件: AndroidCaseIndexTable.java
public int loadIntoIndexTable(HashMap<String, Vector<Integer>> indexCache, String indexName) {
    int resultsReturned = 0;
    String[] args = new String[]{indexName};
    if (SqlStorage.STORAGE_OUTPUT_DEBUG) {
        String query = String.format("SELECT %s,%s %s FROM %s where %s = '%s'", COL_CASE_RECORD_ID, COL_INDEX_NAME, COL_INDEX_TARGET, TABLE_NAME, COL_INDEX_NAME, indexName);
        DbUtil.explainSql(db, query, null);
    }

    Cursor c = db.query(TABLE_NAME, new String[]{COL_CASE_RECORD_ID, COL_INDEX_NAME, COL_INDEX_TARGET},COL_INDEX_NAME + " = ?", args, null, null, null);

    try {
        if (c.moveToFirst()) {
            while (!c.isAfterLast()) {
                resultsReturned++;
                int id = c.getInt(c.getColumnIndexOrThrow(COL_CASE_RECORD_ID));
                String target = c.getString(c.getColumnIndexOrThrow(COL_INDEX_TARGET));

                String cacheID = indexName + "|" + target;
                Vector<Integer> cache;
                if (indexCache.containsKey(cacheID)){
                    cache = indexCache.get(cacheID);
                } else {
                    cache = new Vector<>();
                }
                cache.add(id);
                indexCache.put(cacheID, cache);
                c.moveToNext();
            }
        }

        return resultsReturned;
    } finally {
        if (c != null) {
            c.close();
        }
    }

}
 
源代码12 项目: ctgi   文件: LonestStringInDictionary.java
public void findLongestString(String word, ArrayList<String> dictionary)
{
	if(word==null || word == "")
		return;
	int count=0;
	HashMap<Character, Boolean> charMap = new HashMap<Character, Boolean>();
	for(int i=0; i< word.length();i++)
	{
		charMap.put(word.charAt(i), true);
	}
	
	for(String str : dictionary)
	{
		count=0;
		for(int j=0;j<str.length();j++)
		{
			if(charMap.containsKey(str.charAt(j)))
			{
				count++;
			}else
				break;
		}
		if(count==str.length())
		{
			if(longestWord==null)
				longestWord=new StringObject(str, str.length());
			else if(longestWord.length<count)
				longestWord=new StringObject(str, count);
		}
	}
}
 
public void afterUpdate(EntryEvent event) {
  super.afterUpdate(event);

  Log.getLogWriter().info("Invoking the durable Listener");

  String key = (String)event.getKey();
  String VmDurableId = ((InternalDistributedSystem)InternalDistributedSystem
      .getAnyInstance()).getConfig().getDurableClientId();

  synchronized (lock) {
    HashMap map = (HashMap)DurableClientsBB.getBB().getSharedMap().get(
        VmDurableId);

    if (!map.containsKey(OPS_KEYS)) {
      map.put(OPS_KEYS, new HashSet());
    }

    HashSet hashSet = (HashSet)map.get(OPS_KEYS);
    hashSet.add(key);
    map.put(OPS_KEYS, hashSet);

    DurableClientsBB.getBB().getSharedMap().put(VmDurableId, map);
    Log.getLogWriter().info(
        "Updated the BB for the afterUpdate for the key " + key
            + " for the event ");
  }

}
 
源代码14 项目: bazel   文件: AspectFunction.java
private void buildSkyKeys(AspectKey key, HashMap<AspectDescriptor, SkyKey> result,
    ImmutableList.Builder<SkyKey> aspectPathBuilder) {
  if (result.containsKey(key.getAspectDescriptor())) {
    return;
  }
  ImmutableList<AspectKey> baseKeys = key.getBaseKeys();
  result.put(key.getAspectDescriptor(), key);
  for (AspectKey baseKey : baseKeys) {
    buildSkyKeys(baseKey, result, aspectPathBuilder);
  }
  // Post-order list of aspect SkyKeys gives the order of propagating aspects:
  // the aspect comes after all aspects it transitively sees.
  aspectPathBuilder.add(key);
}
 
源代码15 项目: netbeans   文件: MenuChecker.java
/** check shortcuts in menu structure
 * @param a
 * @return  
 */
private static StringBuffer checkShortCutCollision(ArrayList a) {
    StringBuffer collisions = new StringBuffer("");
    Iterator it = a.iterator();
    HashMap check = new HashMap();

    while (it.hasNext()) {
        Object o = it.next();

        if (o instanceof NbMenuItem) {
            NbMenuItem item = (NbMenuItem) o;

            if (item.getAccelerator() != null) {
                //stream.println("checking : " + item.name + " - " + item.accelerator);
                if (check.containsKey(item.getAccelerator())) {
                    collisions.append("\n !!!!!! Collision! accelerator ='" + item.getAccelerator() + "' : " + item.getName() + " is in collision with " + check.get(item.getAccelerator()));
                } else {
                    check.put(item.getAccelerator(), item.getName());
                }

            }
        }

        if (o instanceof ArrayList) {
            collisions.append(checkShortCutCollision((ArrayList) o));
        }

    }

    return collisions;
}
 
源代码16 项目: symbolicautomata   文件: SST.java
/**
 * return an equivalent copy without epsilon moves
 */
protected static <P1, F1, S1> SST<P1, F1, S1> removeEpsilonMovesFrom(SST<P1, F1, S1> sst,
		BooleanAlgebraSubst<P1, F1, S1> ba) {

	if (sst.isEpsilonFree)
		return sst;

	Collection<SSTMove<P1, F1, S1>> transitions = new ArrayList<SSTMove<P1, F1, S1>>();
	Map<Integer, OutputUpdate<P1, F1, S1>> outputFunction = new HashMap<Integer, OutputUpdate<P1, F1, S1>>();
	Integer initialState;
	Integer numberOfVariables = sst.variableCount;

	HashMap<Collection<Integer>, Integer> reachedStates = new HashMap<Collection<Integer>, Integer>();
	HashMap<Integer, Map<Integer, SimpleVariableUpdate<P1, F1, S1>>> statesAss = new HashMap<Integer, Map<Integer, SimpleVariableUpdate<P1, F1, S1>>>();
	LinkedList<Collection<Integer>> toVisitStates = new LinkedList<Collection<Integer>>();

	// Add initial state
	Map<Integer, SimpleVariableUpdate<P1, F1, S1>> epsclInitial = sst.getSSTEpsClosure(sst.initialState, ba);
	Collection<Integer> p = epsclInitial.keySet();
	initialState = 0;
	statesAss.put(initialState, epsclInitial);

	reachedStates.put(p, initialState);
	toVisitStates.add(p);

	while (!toVisitStates.isEmpty()) {
		Collection<Integer> currState = toVisitStates.removeFirst();
		int currStateId = reachedStates.get(currState);
		Map<Integer, SimpleVariableUpdate<P1, F1, S1>> stateToAss = statesAss.get(currStateId);

		// set final state
		Integer fin = null;
		for (Integer st : currState) {
			if (sst.isFinalState(st))
				if (fin != null) {
					throw new IllegalArgumentException("two different final states are reachable via epsilon;");
				} else {
					fin = st;
				}
		}
		// set output state if one of the esp closure state is final
		if (fin != null) {
			outputFunction.put(currStateId, stateToAss.get(fin).composeWith(sst.outputFunction.get(fin)));
		}

		for (SSTInputMove<P1, F1, S1> t1 : sst.getInputMovesFrom(currState)) {

			Map<Integer, SimpleVariableUpdate<P1, F1, S1>> epsClosure = sst.getSSTEpsClosure(t1.to, ba);
			Collection<Integer> nextState = epsClosure.keySet();

			int nextStateId = 0;
			if (!reachedStates.containsKey(nextState)) {
				int index = reachedStates.size();
				reachedStates.put(nextState, index);
				toVisitStates.add(nextState);
				statesAss.put(index, epsClosure);
				nextStateId = index;
			} else {
				nextStateId = reachedStates.get(nextState);
			}

			@SuppressWarnings("unchecked")
			SSTInputMove<P1, F1, S1> tnew = (SSTInputMove<P1, F1, S1>) t1.clone();
			tnew.from = currStateId;
			tnew.to = nextStateId;

			tnew.variableUpdate = stateToAss.get(t1.from).composeWith(t1.variableUpdate);

			transitions.add(tnew);
		}

	}

	return MkSST(transitions, initialState, numberOfVariables, outputFunction, ba);
}
 
源代码17 项目: gemfirexd-oss   文件: TUNNEL.java
void handleConfigEvent(HashMap map) {
    if(map == null) return;
    if(map.containsKey("additional_data"))
        additional_data=(byte[])map.get("additional_data");
}
 
源代码18 项目: hadoop   文件: AzureNativeFileSystemStore.java
private static boolean retrieveFolderAttribute(CloudBlobWrapper blob) {
  HashMap<String, String> metadata = blob.getMetadata();
  return null != metadata
      && (metadata.containsKey(IS_FOLDER_METADATA_KEY) || metadata
          .containsKey(OLD_IS_FOLDER_METADATA_KEY));
}
 
源代码19 项目: dragonwell8_jdk   文件: XMBeanAttributes.java
protected void addTableData(DefaultTableModel tableModel,
                            XMBean mbean,
                            MBeanAttributeInfo[] attributesInfo,
                            HashMap<String, Object> attributes,
                            HashMap<String, Object> unavailableAttributes,
                            HashMap<String, Object> viewableAttributes) {

    Object rowData[] = new Object[2];
    int col1Width = 0;
    int col2Width = 0;
    for (int i = 0; i < attributesInfo.length; i++) {
        rowData[0] = (attributesInfo[i].getName());
        if (unavailableAttributes.containsKey(rowData[0])) {
            rowData[1] = Messages.UNAVAILABLE;
        } else if (viewableAttributes.containsKey(rowData[0])) {
            rowData[1] = viewableAttributes.get(rowData[0]);
            if (!attributesInfo[i].isWritable() ||
                !Utils.isEditableType(attributesInfo[i].getType())) {
                rowData[1] = getZoomedCell(mbean, (String) rowData[0], rowData[1]);
            }
        } else {
            rowData[1] = attributes.get(rowData[0]);
        }

        tableModel.addRow(rowData);

        //Update column width
        //
        String str = null;
        if(rowData[0] != null) {
            str = rowData[0].toString();
            if(str.length() > col1Width)
                col1Width = str.length();
        }
        if(rowData[1] != null) {
            str = rowData[1].toString();
            if(str.length() > col2Width)
                col2Width = str.length();
        }
    }
    updateColumnWidth(col1Width, col2Width);
}
 
源代码20 项目: algorithms101   文件: Trie.java
public void insert(String word) {
    HashMap<Character, TrieNode> children = root.children;

    // for each letter in the word string...
    for (int i=0; i < word.length(); i++) {
        char c = word.charAt(i);

        // See if there is a node already representing this letter

        // if there is
        // get it
        // else create it with it's own internal HashMap of letters

        TrieNode n;
        if (children.containsKey(c)) {
            n = children.get(c);
        } else {
            n = new TrieNode(c);
            children.put(c, n);
        }

        // this is the magic line here...
        children = n.children;

        // Take this newly created, or found, node
        // And reset the children variable to point to it's children
        //
        // This is how we continuously step further down the try
        // and insert more letters (even repeating letters) deeper in the
        // data structure.
        //
        // Now when we loop again, we will will loop from here
        // And insert the next letters from this starting point in the word


        // Set this flag to represent that this node is also a full word
        if (i == word.length() - 1) {
            n.isWholeWord = true;
        }
    }
}