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

The following are Jave code examples for showing how to use containsKey() of the java.util.HashMap 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: ctsms   File: EcrfFieldValueAuditTrailLogEagerModel.java   View Source Code Vote up 6 votes
public static EcrfFieldValueAuditTrailLogEagerModel getCachedAuditTrailLogModel(ProbandListEntryOutVO listEntry,
		HashMap<Long, EcrfFieldValueAuditTrailLogEagerModel> auditTrailLogModelCache) {
	EcrfFieldValueAuditTrailLogEagerModel model;
	if (listEntry != null && auditTrailLogModelCache != null) {
		long listEntryId = listEntry.getId();
		if (auditTrailLogModelCache.containsKey(listEntryId)) {
			model = auditTrailLogModelCache.get(listEntryId);
		} else {
			model = new EcrfFieldValueAuditTrailLogEagerModel();
			model.setListEntryId(listEntryId);
			auditTrailLogModelCache.put(listEntryId, model);
		}
	} else {
		model = new EcrfFieldValueAuditTrailLogEagerModel();
	}
	return model;
}
 
Example 2
Project: human-mobility-modeling-utilities   File: LocationTraceHelper.java   View Source Code Vote up 6 votes
/**
 * This methods returns a unique location Id number list using given trace list.
 * @param traces trace list
 * @return unique ids in a list
 */
public HashMap<Long,Integer> extractUniqueLocationIdCounts(
		List<ExtendedLocationTrace> traces) {
	HashMap<Long,Integer> idMap = new HashMap<Long, Integer>();
	
	for(ExtendedLocationTrace aTrace: traces){
		
		// all location ids start from 1. if there is a lower number, it is likely that DBSCAN assigned noise to that visit
		if(aTrace.getLocationId()>0){ 
			int count = 0;
			
			if (idMap.containsKey(aTrace.getLocationId()) == true){
				count = idMap.get(aTrace.getLocationId());
			}
			count++;
			idMap.put(aTrace.getLocationId(), count);
		}
	}
	return idMap ;
}
 
Example 3
Project: ctsms   File: CollidingVisitScheduleItemEagerModel.java   View Source Code Vote up 6 votes
public static CollidingVisitScheduleItemEagerModel getCachedCollidingVisitScheduleItemModel(ProbandStatusEntryOutVO statusEntry, boolean allProbandGroups,
		HashMap<Long, CollidingVisitScheduleItemEagerModel> collidingVisitScheduleItemModelCache) {
	CollidingVisitScheduleItemEagerModel model;
	if (statusEntry != null && collidingVisitScheduleItemModelCache != null) {
		long probandStatusEntryId = statusEntry.getId();
		if (collidingVisitScheduleItemModelCache.containsKey(probandStatusEntryId)) {
			model = collidingVisitScheduleItemModelCache.get(probandStatusEntryId);
		} else {
			model = new CollidingVisitScheduleItemEagerModel(probandStatusEntryId, allProbandGroups);
			collidingVisitScheduleItemModelCache.put(probandStatusEntryId, model);
		}
	} else {
		model = new CollidingVisitScheduleItemEagerModel(allProbandGroups);
	}
	return model;
}
 
Example 4
Project: mutaflow   File: FlowExtractor.java   View Source Code Vote up 6 votes
/**
	 * Reports how often a sink occurred and how often it occurred without a source
	 * @param sinks
	 * @param sources
	 */
	private static void occurenceAdderSink(HashMap<String, HashSet<String>> sinks, HashMap<String, HashSet<String>> sources, HashMap<String, Integer> sinksOccurred, HashMap<String, Integer> sinksOccurredNoSource) {
		for (String sink : sinks.keySet()) {
//			System.out.println(sink);
			if (sinksOccurred.containsKey(sink)) {
				sinksOccurred.put(sink, sinksOccurred.get(sink)+1);
			} else {
				sinksOccurred.put(sink, 1);
				sinksOccurredNoSource.put(sink,0);
			}
			
			if (sources.isEmpty()) {
				sinksOccurredNoSource.put(sink, sinksOccurredNoSource.get(sink)+1);
			}
		}
	}
 
Example 5
Project: athena   File: SrlgGraphSearch.java   View Source Code Vote up 6 votes
/**
 * Creates an SRLG graph search object from a map, inferring
 * the number of groups and creating an integral mapping.
 *
 * @param   grouping    map linking edges to object group assignments,
 *                      with same-group status linked to equality
 */
public SrlgGraphSearch(Map<E, Object> grouping) {
    if (grouping == null) {
        useSuurballe = true;
        return;
    }
    numGroups = 0;
    HashMap<Object, Integer> tmpMap = new HashMap<>();
    riskGrouping = new HashMap<>();
    for (E key: grouping.keySet()) {
        Object value = grouping.get(key);
        if (!tmpMap.containsKey(value)) {
            tmpMap.put(value, numGroups);
            numGroups++;
        }
        riskGrouping.put(key, tmpMap.get(value));
    }
}
 
Example 6
Project: CouponsTracker   File: CouponsTrackerNotification.java   View Source Code Vote up 6 votes
@Override
protected HashMap<String, Integer> doInBackground(Void... params) {
    Cursor cursor = context.getContentResolver().query(
            CouponContract.CouponTable.URI,
            CouponContract.CouponTable.PROJECTION,
            CouponContract.CouponTable.COLUMN_VALID_UNTIL + " = ?",
            new String[]{ String.valueOf(Utilities.getLongDateToday()) },
            CouponContract.CouponTable.COLUMN_VALID_UNTIL
    );
    if (cursor == null) {
        return null;
    }

    HashMap<String, Integer> merchantCouponCountMap = new HashMap<>();
    while (cursor.moveToNext()) {
        Coupon coupon = Coupon.getCoupon(cursor);
        int count = 1;
        if (merchantCouponCountMap.containsKey(coupon.merchant)) {
            count += merchantCouponCountMap.get(coupon.merchant);
        }
        merchantCouponCountMap.put(coupon.merchant, count);
    }
    return merchantCouponCountMap;
}
 
Example 7
Project: ctsms   File: ReimbursementsBean.java   View Source Code Vote up 6 votes
public MoneyTransferSummaryVO getOpenNoParticipationSummary(ProbandOutVO proband) {
	if (trialId != null && proband != null) {
		HashMap<Long, MoneyTransferSummaryVO> cache;
		MoneyTransferSummaryVO summary;
		if (noParticipationOpenSummaryCache.containsKey(trialId)) {
			cache = noParticipationOpenSummaryCache.get(trialId);
			if (cache.containsKey(proband.getId())) {
				summary = cache.get(proband.getId());
			} else {
				summary = WebUtil.getProbandOpenReimbursementSummary(trialId, proband.getId(), null);
				cache.put(proband.getId(), summary);
			}
		} else {
			cache = new HashMap<Long, MoneyTransferSummaryVO>();
			noParticipationOpenSummaryCache.put(trialId, cache);
			summary = WebUtil.getProbandOpenReimbursementSummary(trialId, proband.getId(), null);
			cache.put(proband.getId(), summary);
		}
		return summary;
	}
	return null;
}
 
Example 8
Project: ctsms   File: ProbandListEntryTagValueBean.java   View Source Code Vote up 6 votes
private void setInputModelErrorMsgs(Object data) {
	HashMap<Long, String> errorMessagesMap;
	try {
		errorMessagesMap = (HashMap<Long, String>) data;
	} catch (ClassCastException e) {
		errorMessagesMap = null;
	}
	if (errorMessagesMap != null && errorMessagesMap.size() > 0) {
		Iterator<ProbandListEntryTagInputModel> it = inputModels.iterator();
		while (it.hasNext()) {
			ProbandListEntryTagInputModel inputModel = it.next();
			if (errorMessagesMap.containsKey(inputModel.getProbandListTagId())) {
				inputModel.setErrorMessage(errorMessagesMap.get(inputModel.getProbandListTagId()));
			} else {
				inputModel.setErrorMessage(null);
			}
		}
	} else {
		clearInputModelErrorMsgs();
	}
}
 
Example 9
Project: MFM   File: MAME_Game_Prefixes.java   View Source Code Vote up 6 votes
private void countGames(HashMap<String, AtomicInteger> hm, int length, String startsWith) {
    for (String game : games) {
        String str = null;
        if (game.length() >= length) {
            str = game.substring(0, length);
        }
        if (str != null && (startsWith == null || str.startsWith(startsWith))) {
            if (hm.containsKey(str)) {
                hm.get(str).incrementAndGet();
            } else {
                hm.put(str, new AtomicInteger(1));
            }
        }
    }
    if (length == 1) {
        checkKeys(hm, length);
    }
}
 
Example 10
Project: labtablet   File: FavoriteDetailsActivity.java   View Source Code Vote up 6 votes
/**
 * Generates the necessary files for the forms upload to the SeaBioData repository
 */
private void dispatchSBDExport() throws IOException {


    SharedPreferences settings = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);

    if (!settings.contains(Utils.TAG_SBD_USERNAME)) {
        Toast.makeText(this, getString(R.string.sbd_username_missing_export), Toast.LENGTH_SHORT).show();
        return;
    }

    HashMap<String, ArrayList<FormInstance>> groupedInstances = new HashMap<>();
    for (FormInstance fi : currentItem.getLinkedForms()) {
        if (groupedInstances.containsKey(fi.getParent())) {
            groupedInstances.get(fi.getParent()).add(fi);
            continue;
        }

        ArrayList<FormInstance> newInstances = new ArrayList<>();
        newInstances.add(fi);
        groupedInstances.put(fi.getParent(), newInstances);
    }


    for (String key : groupedInstances.keySet()) {
        FormExportItem exportItem = new FormExportItem(groupedInstances.get(key), settings.getString(Utils.TAG_SBD_USERNAME, ""));
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + key + "_" + new Date().toString() + ".json");

        if(file.createNewFile()) {
            OutputStream fo = new FileOutputStream(file);
            fo.write(new Gson().toJson(exportItem).getBytes());
            fo.close();
        }
    }

    Toast.makeText(getApplicationContext(), getString(R.string.sbd_dorms_exported_successfully), Toast.LENGTH_SHORT).show();
}
 
Example 11
Project: SparkSeq   File: AlleleBalanceBySample.java   View Source Code Vote up 6 votes
private Double annotateWithPileup(final AlignmentContext stratifiedContext, final VariantContext vc) {

        final HashMap<Byte, Integer> alleleCounts = new HashMap<>();
        for (final Allele allele : vc.getAlleles())
            alleleCounts.put(allele.getBases()[0], 0);

        final ReadBackedPileup pileup = stratifiedContext.getBasePileup();
        for (final PileupElement p : pileup) {
            if (alleleCounts.containsKey(p.getBase()))
                alleleCounts.put(p.getBase(), alleleCounts.get(p.getBase()) + 1);
        }

        // we need to add counts in the correct order
        final int[] counts = new int[alleleCounts.size()];
        counts[0] = alleleCounts.get(vc.getReference().getBases()[0]);
        for (int i = 0; i < vc.getAlternateAlleles().size(); i++)
            counts[i + 1] = alleleCounts.get(vc.getAlternateAllele(i).getBases()[0]);

        // sanity check
        if (counts[0] + counts[1] == 0)
            return null;

        return ((double) counts[0] / (double) (counts[0] + counts[1]));
    }
 
Example 12
Project: java-learn   File: TwoSum.java   View Source Code Vote up 5 votes
public int[] twoSum(int[] nums, int target) {
    int len = nums.length;
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < len; ++i) {
        if (map.containsKey(nums[i])) {
            return new int[]{map.get(nums[i]), i};
        }
        map.put(target - nums[i], i);
    }
    return null;
}
 
Example 13
Project: javaide   File: GetSetViewOfKeysFromHashMapExample.java   View Source Code Vote up 5 votes
public static void main(String[] args) {

    //create HashMap object
    HashMap hMap = new HashMap();

    //add key value pairs to HashMap
    hMap.put("1", "One");
    hMap.put("2", "Two");
    hMap.put("3", "Three");

    /*
      get Set of keys contained in HashMap using
      Set keySet() method of HashMap class
    */

    Set st = hMap.keySet();

    System.out.println("Set created from HashMap Keys contains :");
    //iterate through the Set of keys
    Iterator itr = st.iterator();
    while (itr.hasNext()) System.out.println(itr.next());

    /*
       Please note that resultant Set object is backed by the HashMap.
       Any key that is removed from Set will also be removed from
       original HashMap object. The same is not the case with the element
       addition.
    */

    //remove 2 from Set
    st.remove("2");

    //check if original HashMap still contains 2
    boolean blnExists = hMap.containsKey("2");
    System.out.println("Does HashMap contain 2 ? " + blnExists);
  }
 
Example 14
Project: mutaflow   File: FlowExtractor.java   View Source Code Vote up 5 votes
/**
 * Reports Flows where the sink did not occur for all mutated files. It also reports how often a sink occurred and whether it occurred for files where no source was mutated.
 * @param flowocc
 * @param sinkCounter
 * @param occurredForNoSource
 * @param fileCounter
 * @param writer
 * @param flowPosition 
 * @param crashReports 
 */
private static void occurrenceAnalyzer(HashMap<String, HashMap<String, Integer>> flowocc, HashMap<String, Integer> sinkCounter, HashSet<String> occurredForNoSource,float fileCounter, int noMutationCounter, 
		PrintWriter writer, HashMap<String, HashMap<String, String>> flowPosition, HashMap<String, HashMap<String, Boolean>> crashReports, HashMap<String, HashSet<String>> refoundFlows) {
	if (notCondensed) {
		writer.write("\nDroidMutant found the following flows. Such without a number indicate flows, where a value was again found in the sink: \n");
	}
	for (Entry<String, HashSet<String>> ent : refoundFlows.entrySet()) {
		for (String sink : ent.getValue()) {
			writer.write(ent.getKey()+"\t"+sink+"\n");
			refoundCounter++;
		}
	}
	
	for (Entry<String,HashMap<String, Integer>> sourceEntry : flowocc.entrySet()) {
		for (Entry<String,Integer> sinkEntry : sourceEntry.getValue().entrySet()) {
			if (!sinkCounter.get(sinkEntry.getKey()).equals(fileCounter)) {  //if sink did not occur for all mutated files
				float sinkCount = sinkCounter.get(sinkEntry.getKey());
				if (!occurredForNoSource.contains(sinkEntry.getKey())) {
					if ((!refoundFlows.containsKey(sourceEntry.getKey())) || (!refoundFlows.get(sourceEntry.getKey()).contains(sinkEntry.getKey()))) {
						writer.write(sourceEntry.getKey()+"\t"+sinkEntry.getKey()+"\t"+sinkCount+"\t"+fileCounter + "\t" + (occurredForNoSource.contains(sinkEntry.getKey()) ? 0 : 1)+"\t"+noMutationCounter+ "\n");
					}
					HashMap<String, Boolean> currentAPKMap = crashReports.get(FlowExtractor.currentAPK);

					//crashes with NPE if Converter was not run firstly
					boolean crashed = false;

					
					System.out.println(flowPosition.get(sourceEntry.getKey()).get(sinkEntry.getKey()) +" " + sourceEntry.getKey() + " " + sinkEntry.getKey() + " " + crashed );
				}
			}
		}
	}
}
 
Example 15
Project: sbc-qsystem   File: QReportsList.java   View Source Code Vote up 5 votes
private boolean checkLogin(HttpRequest request) {
    boolean res = false;
    // в запросе должен быть пароль и пользователь, если нету, то отказ на вход
    String entityContent = NetUtil.getEntityContent(request);
    QLog.l().logger().trace("Принятые параметры \"" + entityContent + "\".");
    // ресурс для выдачи в браузер. это либо список отчетов при корректном логининге или отказ на вход
    // разбирем параметры
    final HashMap<String, String> cookie = NetUtil.getCookie(entityContent, "&");
    if (cookie.containsKey("username") && cookie.containsKey("password")) {
        if (isTrueUser(cookie.get("username"), cookie.get("password"))) {
            res = true;
        }
    }
    return res;
}
 
Example 16
Project: chexmix   File: ChExMixConfig.java   View Source Code Vote up 5 votes
/**
 * Merge a set of estimated genomes 
 * @param estGenomes
 * @return
 */
public Genome mergeGenomes(List<Genome> estGenomes){
	//Combine the chromosome information
	HashMap<String, Integer> chrLenMap = new HashMap<String, Integer>();
	for(Genome e : estGenomes){
		Map<String, Integer> currMap = e.getChromLengthMap();
		for(String s: currMap.keySet()){
			if(!chrLenMap.containsKey(s) || chrLenMap.get(s)<currMap.get(s))
				chrLenMap.put(s, currMap.get(s));
		}
	}
	gen =new Genome("Genome", chrLenMap);
	return gen;		
}
 
Example 17
Project: smaph   File: FeaturePack.java   View Source Code Vote up 5 votes
public FeaturePack(HashMap<String, Double> features){
	if (features == null)
		return;
	checkFeatures(features);
	featuresArray = new double[this.getFeatureCount()];
	
	for (String ftrName : getFeatureNames())
		featuresArray[ftrNameToArrayPosition(ftrName)] = features
				.containsKey(ftrName) ? features.get(ftrName) : Double.NaN;
}
 
Example 18
Project: eagle-oj-api   File: UserService.java   View Source Code Vote up 5 votes
public List<HashMap<String, Object>> getModeratorsInUidList(List<Integer> uidList) {
    List<HashMap<String, Object>> moderators = userDao.getModeratorsInUidList(sqlSession, uidList);
    for (HashMap<String, Object> map: moderators) {
        if (! map.containsKey("avatar")) {
            map.put("avatar", DEFAULT_AVATAR);
        }
    }
    return moderators;
}
 
Example 19
Project: ctsms   File: ServiceUtil.java   View Source Code Vote up 4 votes
private static boolean updateBookingSummaryDetail(Long key,
		HashMap<Long, InventoryBookingDurationSummaryDetailVO> durationSummaryDetailsMap,
		ArrayList<InventoryBookingDurationSummaryDetailVO> assigned,
		InventoryOutVO inventory,
		CourseOutVO course,
		ProbandOutVO proband,
		TrialOutVO trial,
		InventoryBookingOutVO booking,
		InventoryBookingDurationSummaryVO summary,
		boolean fullBookings,
		boolean mergeOverlapping) {
	if (key != null) {
		InventoryBookingDurationSummaryDetailVO durationSummaryDetail = null;
		if (durationSummaryDetailsMap.containsKey(key)) {
			durationSummaryDetail = durationSummaryDetailsMap.get(key);
		} else {
			durationSummaryDetail = new InventoryBookingDurationSummaryDetailVO();
			durationSummaryDetailsMap.put(key, durationSummaryDetail);
			assigned.add(durationSummaryDetail);
			durationSummaryDetail.setInventory(inventory);
			durationSummaryDetail.setProband(proband);
			durationSummaryDetail.setCourse(course);
			durationSummaryDetail.setTrial(trial);
			durationSummaryDetail.setBookingCount(0);
			if (!mergeOverlapping) {
				durationSummaryDetail.setTotalDuration(0l);
			}
		}
		if (!fullBookings) {
			Date start = booking.getStart();
			Date stop = booking.getStop();
			boolean exceeds = false;
			if (summary.getStart() != null && booking.getStart().before(summary.getStart())) {
				start = summary.getStart();
				exceeds = true;
			}
			if (summary.getStop() != null && booking.getStop().after(summary.getStop())) {
				stop = summary.getStop();
				exceeds = true;
			}
			if (exceeds) {
				BookingDuration bookingDuration = new BookingDuration();
				try {
					bookingDuration.add(start, stop, null);
					bookingDuration.updateInventoryBooking(booking);
				} catch (Exception e) {
				}
			}
		}
		durationSummaryDetail.setBookingCount(durationSummaryDetail.getBookingCount() + 1);
		if (!mergeOverlapping) {
			durationSummaryDetail.setTotalDuration(durationSummaryDetail.getTotalDuration() + booking.getTotalDuration());
			if (summary.getIntervalDuration() > 0.0f) { // summary.getInventory() != null &&
				durationSummaryDetail.setLoad(((float) durationSummaryDetail.getTotalDuration()) / ((float) summary.getIntervalDuration()));
			}
		}
		return true;
	}
	return false;
}
 
Example 20
Project: elasticsearch_my   File: PolygonBuilder.java   View Source Code Vote up 4 votes
/**
 * This method sets the component id of all edges in a ring to a given id and shifts the
 * coordinates of this component according to the dateline
 *
 * @param edge An arbitrary edge of the component
 * @param id id to apply to the component
 * @param edges a list of edges to which all edges of the component will be added (could be <code>null</code>)
 * @return number of edges that belong to this component
 */
private static int component(final Edge edge, final int id, final ArrayList<Edge> edges) {
    // find a coordinate that is not part of the dateline
    Edge any = edge;
    while(any.coordinate.x == +DATELINE || any.coordinate.x == -DATELINE) {
        if((any = any.next) == edge) {
            break;
        }
    }

    double shiftOffset = any.coordinate.x > DATELINE ? DATELINE : (any.coordinate.x < -DATELINE ? -DATELINE : 0);
    if (debugEnabled()) {
        LOGGER.debug("shift: [{}]", shiftOffset);
    }

    // run along the border of the component, collect the
    // edges, shift them according to the dateline and
    // update the component id
    int length = 0, connectedComponents = 0;
    // if there are two connected components, splitIndex keeps track of where to split the edge array
    // start at 1 since the source coordinate is shared
    int splitIndex = 1;
    Edge current = edge;
    Edge prev = edge;
    // bookkeep the source and sink of each visited coordinate
    HashMap<Coordinate, Tuple<Edge, Edge>> visitedEdge = new HashMap<>();
    do {
        current.coordinate = shift(current.coordinate, shiftOffset);
        current.component = id;

        if (edges != null) {
            // found a closed loop - we have two connected components so we need to slice into two distinct components
            if (visitedEdge.containsKey(current.coordinate)) {
                if (connectedComponents > 0 && current.next != edge) {
                    throw new InvalidShapeException("Shape contains more than one shared point");
                }

                // a negative id flags the edge as visited for the edges(...) method.
                // since we're splitting connected components, we want the edges method to visit
                // the newly separated component
                final int visitID = -id;
                Edge firstAppearance = visitedEdge.get(current.coordinate).v2();
                // correct the graph pointers by correcting the 'next' pointer for both the
                // first appearance and this appearance of the edge
                Edge temp = firstAppearance.next;
                firstAppearance.next = current.next;
                current.next = temp;
                current.component = visitID;
                // backtrack until we get back to this coordinate, setting the visit id to
                // a non-visited value (anything positive)
                do {
                    prev.component = visitID;
                    prev = visitedEdge.get(prev.coordinate).v1();
                    ++splitIndex;
                } while (!current.coordinate.equals(prev.coordinate));
                ++connectedComponents;
            } else {
                visitedEdge.put(current.coordinate, new Tuple<Edge, Edge>(prev, current));
            }
            edges.add(current);
            prev = current;
        }
        length++;
    } while(connectedComponents == 0 && (current = current.next) != edge);

    return (splitIndex != 1) ? length-splitIndex: length;
}