Java Code Examples for java.util.HashMap#containsKey()

The following examples show how to use java.util.HashMap#containsKey() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DPCoinChange.java    From Hackerrank-Solutions with MIT License 6 votes vote down vote up
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;
}
 
Example 2
Source File: ConferenceAction.java    From owt-client-android with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example 3
Source File: StringUtils.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
}
 
Example 4
Source File: HueMulator.java    From ha-bridge with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: Solution.java    From codekata with MIT License 6 votes vote down vote up
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);
}
 
Example 6
Source File: EntityKeyFilterer.java    From commcare-android with Apache License 2.0 6 votes vote down vote up
@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));
        }
    }
}
 
Example 7
Source File: RemoteParForUtils.java    From systemds with Apache License 2.0 6 votes vote down vote up
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]);
}
 
Example 8
Source File: VOCacheContext.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
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;
}
 
Example 9
Source File: DFSAdmin.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 10
Source File: AndroidCaseIndexTable.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
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();
        }
    }

}
 
Example 11
Source File: LonestStringInDictionary.java    From ctgi with MIT License 5 votes vote down vote up
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);
		}
	}
}
 
Example 12
Source File: DynamicInterestEventListener.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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 ");
  }

}
 
Example 13
Source File: AspectFunction.java    From bazel with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: MenuChecker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example 15
Source File: Inspect.java    From beakerx with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 16
Source File: AzureNativeFileSystemStore.java    From hadoop with Apache License 2.0 4 votes vote down vote up
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));
}
 
Example 17
Source File: XMBeanAttributes.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
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);
}
 
Example 18
Source File: TUNNEL.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
void handleConfigEvent(HashMap map) {
    if(map == null) return;
    if(map.containsKey("additional_data"))
        additional_data=(byte[])map.get("additional_data");
}
 
Example 19
Source File: Trie.java    From algorithms101 with MIT License 4 votes vote down vote up
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;
        }
    }
}
 
Example 20
Source File: SST.java    From symbolicautomata with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}