Java Code Examples for java.util.TreeMap#keySet()

The following examples show how to use java.util.TreeMap#keySet() . 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: GFXDReport.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public TreeMap<String, Integer> getWorstBugs(ArrayList<JUnitResultData> junitOutFileSummaries, int minimumInstances) {
  // Build a map of the bug to its frequency
  TreeMap<String, Integer> bugToFailCount = new TreeMap<String, Integer>();
  for (JUnitResultData fileSummary : junitOutFileSummaries) {
    for (JUnitResult testFailure : fileSummary.getFailures()) {
      if (testFailure.getAssociatedKnownFailure() != null &&
          testFailure.getAssociatedKnownFailure().getBug() != null) {
        String bugNumber = testFailure.getAssociatedKnownFailure().getBug();
        if (bugNumber.trim().length() > 0) {
          Integer priorCount = bugToFailCount.get(bugNumber) == null ? 0: bugToFailCount.get(bugNumber);
          bugToFailCount.put(bugNumber, priorCount+1);
        }
      }
    }
  }
  // Filter the bugmap by minimum count
  TreeMap<String, Integer> returnMap = new TreeMap<String, Integer>();
  for (String bugNum : bugToFailCount.keySet()) {
    if (bugToFailCount.get(bugNum) >= minimumInstances) {
      returnMap.put(bugNum, bugToFailCount.get(bugNum));
    }
  }
  return returnMap;
}
 
Example 2
Source File: LongHashMapTest.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public void checkEquals(LongMap<String> v1, TreeMap<Long, String> v2) {
    assertEquals(v1.size(), v2.size());
    for (long k : v2.keySet()) {
        assertEquals(v1.get(k), v2.get(k));
    }

    int counter = 0;
    Iterator<String> it = v1.valuesIterator();
    while (it.hasNext()) {
        String v = it.next();
        long key = Long.parseLong(v);
        assertEquals(v1.get(key), v);
        assertEquals("" + key, v);
        counter++;
    }
    assertEquals(counter, v2.size());
}
 
Example 3
Source File: ConsumerStatusSubCommand.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void printRebalanceResult(TreeMap<String, ConsumerRunningInfo> criTable) {
    if (criTable == null || criTable.isEmpty()) {
        System.out.printf("Empty Result: criTable is empty.\n");
        return;
    }
    Map<MessageQueue, String> rbResult = new TreeMap<MessageQueue, String>();
    for (String cid : criTable.keySet()) {
        for (MessageQueue messageQueue : criTable.get(cid).getMqTable().keySet()) {
            rbResult.put(messageQueue, cid);
        }
    }
    String format = "%30s|%20s|%10s| %s\n";
    System.out.printf("--------------------------------------------------------------------------------------------------\n");
    System.out.printf(format, "Topic","Broker Name", "QueueId", "ConsumerClientId");
    System.out.printf("--------------------------------------------------------------------------------------------------\n");
    for (Entry<MessageQueue, String> entry : rbResult.entrySet()) {
        System.out.printf(format, entry.getKey().getTopic(), entry.getKey().getBrokerName(),
                entry.getKey().getQueueId(), entry.getValue());
    }

}
 
Example 4
Source File: GetReportData.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
private JSONObject extractSummaryData(HashMap<String, SummaryStatisticsDTO> summaryMap, SummaryStatisticsDTO total) throws JSONException {
    JSONObject extract = new JSONObject();
    JSONArray dataArray = new JSONArray();
    Gson gson = new Gson();
    //sort keys
    TreeMap<String, SummaryStatisticsDTO> sortedKeys = new TreeMap<>(summaryMap);
    for (String key : sortedKeys.keySet()) {
        SummaryStatisticsDTO sumStats = summaryMap.get(key);
        //percentage values
        sumStats.updatePercentageStatistics();
        dataArray.put(new JSONObject(gson.toJson(sumStats)));
    }
    total.updatePercentageStatistics();

    extract.put("split", dataArray);
    extract.put("total", new JSONObject(gson.toJson(total)));
    return extract;
}
 
Example 5
Source File: FileManager.java    From ApexDoc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void createClassGroupContent(TreeMap<String, String> mapFNameToContent, String links, String projectDetail,
        TreeMap<String, ClassGroup> mapGroupNameToClassGroup,
        ArrayList<ClassModel> cModels, IProgressMonitor monitor) {

    for (String strGroup : mapGroupNameToClassGroup.keySet()) {
        ClassGroup cg = mapGroupNameToClassGroup.get(strGroup);
        if (cg.getContentSource() != null) {
            String cgContent = parseHTMLFile(cg.getContentSource());
            if (cgContent != "") {
                String strHtml = Constants.getHeader(projectDetail) + links + "<td class='contentTD'>" +
                        "<h2 class='section-title'>" +
                        escapeHTML(cg.getName()) + "</h2>" + cgContent + "</td>";
                strHtml += Constants.FOOTER;
                mapFNameToContent.put(cg.getContentFilename(), strHtml);
                if (monitor != null)
                    monitor.worked(1);
            }
        }
    }
}
 
Example 6
Source File: ClientCallableStatement.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Override
protected void initializeProcedureOutParams(StatementResult sr) {
  final TreeMap<Integer, OutputParameter> outParams = this.outParams;
  if (outParams != null) {
    if ((this.outParamValues = sr.getProcedureOutParams()) != null) {
      setCurrentSource(gfxdConstants.BULK_CLOSE_STATEMENT, statementId,
          null);
      this.outParamsPositionInRow = new TIntIntHashMap(outParams.size());
      // starting index at 1 since get on TIntIntHashMap will give 0 if absent
      int outIndex = 1;
      for (Integer parameterIndex : outParams.keySet()) {
        this.outParamsPositionInRow.put(parameterIndex.intValue(), outIndex);
        outIndex++;
      }
    }
  }
}
 
Example 7
Source File: Solution.java    From java-technology-stack with MIT License 6 votes vote down vote up
public List<Integer> topKFrequent(int[] nums, int k) {

        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int num: nums){
            if(map.containsKey(num))
                map.put(num, map.get(num) + 1);
            else
                map.put(num, 1);
        }

        PriorityQueue<Freq> pq = new PriorityQueue<>();
        for(int key: map.keySet()){
            if(pq.getSize() < k)
                pq.enqueue(new Freq(key, map.get(key)));
            else if(map.get(key) > pq.getFront().freq){
                pq.dequeue();
                pq.enqueue(new Freq(key, map.get(key)));
            }
        }

        LinkedList<Integer> res = new LinkedList<>();
        while(!pq.isEmpty())
            res.add(pq.dequeue().e);
        return res;
    }
 
Example 8
Source File: CollatzSequenceTest.java    From symja_android_library with GNU General Public License v3.0 5 votes vote down vote up
private static void analyzeNStartSequences(TreeMap<Integer, ArrayList<BigInteger>> length2NList) {
	for (int length : length2NList.keySet()) {
		ArrayList<BigInteger> nList = length2NList.get(length);
		//LOG.debug("length=" + length + ": n0List = " + nList);
		int period = findPeriod(nList);
		if (period>0) {
			List<BigInteger> nPeriodList = nList.subList(0, period);
			BigInteger periodDiff = nList.get(period).subtract(nList.get(0));
			LOG.info("length=" + length + ": #n0=" + nList.size() + ", period=" + period + ", periodDiff=" + periodDiff + ", nPeriodList = " + nPeriodList);
		} else {
			LOG.info("length=" + length + ": #n0=" + nList.size() + ", period not identified");
		}
	}
}
 
Example 9
Source File: PublishedAssessmentSettingsBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Returns all groups for site
 * @return
 */
public SelectItem[] getGroupsForSite() {
	SelectItem[] groupSelectItems = new SelectItem[0];
	TreeMap sortedSelectItems = new TreeMap();
	Site site;
	try {
		site = SiteService.getSite(toolManager.getCurrentPlacement()
				.getContext());
		Collection groups = site.getGroups();
		if (groups != null && groups.size() > 0) {
			groupSelectItems = new SelectItem[groups.size()];
			Iterator groupIter = groups.iterator();
			while (groupIter.hasNext()) {
				Group group = (Group) groupIter.next();
				String title = group.getTitle();
				String groupId = group.getId();
                String uniqueTitle = title + groupId;
                sortedSelectItems.put(uniqueTitle.toUpperCase(), new SelectItem(group.getId(), title));
			}
			Set keySet = sortedSelectItems.keySet();
			groupIter = keySet.iterator();
			int i = 0;
			while (groupIter.hasNext()) {
				groupSelectItems[i++] = (SelectItem) sortedSelectItems.get(groupIter.next());
			}
		}
	} catch (IdUnusedException ex) {
		// No site available
	}
	return groupSelectItems;
}
 
Example 10
Source File: MRBase.java    From pattern-matching with Apache License 2.0 5 votes vote down vote up
protected static String mismatchVectorToString(TreeMap<Integer, Float> idToMismatchMap) {
	// build a string vector of model to data node mismatches
	String mismatchVectorAsString = "";
	for (Integer key : idToMismatchMap.keySet()) {
		if (mismatchVectorAsString.length() > 0) {
			mismatchVectorAsString = mismatchVectorAsString + ",";
		}
		mismatchVectorAsString = mismatchVectorAsString + key + "," + idToMismatchMap.get(key);
	}
	return mismatchVectorAsString;
}
 
Example 11
Source File: GFXDReport.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void makeCSVFailureReports(
    TreeMap<String, ArrayList<FailureReportingRow>> failureReportingMap)
    throws Exception {
  for (String outFileName : failureReportingMap.keySet()) {
    PrintWriter csvPW = new PrintWriter(new BufferedWriter(new FileWriter(
        getGfxdReportDir() + "/" + outFileName + ".csv")));
    csvPW.println("Test,Bug#,Bug State,Bug Priority,Failure description");
    for (FailureReportingRow rptRow : failureReportingMap.get(outFileName)) {
      csvPW.println(rptRow.getTestName() + "," + rptRow.getBugNum() + ","
          + rptRow.getBugState() + "," + rptRow.getBugPriority() + ","
          + rptRow.getFailureDescription());
    }
    csvPW.close();
  }
}
 
Example 12
Source File: WXContactTreeNode.java    From SmartIM4IntelliJ with Apache License 2.0 5 votes vote down vote up
public List<VirtualCategory<Contact>> getContactGroup(List<Contact> list) {
    List<VirtualCategory<Contact>> cates = new ArrayList<>();
    if (!IMUtils.isEmpty(list)) {
        List<Contact> unA = new ArrayList<>();
        TreeMap<String, List<Contact>> maps = new TreeMap<>();
        for (Contact c : list) {
            String py = c.getPYInitial();
            char A = IMUtils.isEmpty(py) ? '#' : py.charAt(0);
            if (A >= 'A' && A <= 'Z' || A >= 'a' && A <= 'z') {
                String a = String.valueOf(A).toUpperCase();
                List<Contact> values = maps.get(a);
                if (values == null) {
                    values = new ArrayList<>();
                    maps.put(a, values);
                }
                values.add(c);
            } else {
                unA.add(c);
            }
        }
        for (String n : maps.keySet()) {
            cates.add(new VirtualCategory<>(n, maps.get(n)));
        }
        if (!IMUtils.isEmpty(unA)) {
            cates.add(new VirtualCategory<>("#", unA));
        }
    }
    return cates;
}
 
Example 13
Source File: UserAPIController.java    From onboard with Apache License 2.0 5 votes vote down vote up
private TreeMap<String, List<TodolistDTO>> makeUserCompletedTodosMapSerilizable(TreeMap<Date, List<Todolist>> map) {
    TreeMap<String, List<TodolistDTO>> mapDTO = new TreeMap<String, List<TodolistDTO>>();
    Set<Date> dates = map.keySet();
    for (Date date : dates) {
        List<Todolist> completedTodos = map.get(date);
        mapDTO.put(new SimpleDateFormat("yyyy-MM-dd").format(date),
                Lists.transform(completedTodos, TodolistTransform.TODOLIST_DTO_TODOS_FUNCTION));
    }
    return mapDTO;
}
 
Example 14
Source File: ConcurrentTasksSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void dump(PrintStream stream) {
    TreeMap<String, AtomicInteger> map = new TreeMap<>(counters);

    for (String id : map.keySet()) {
        stream.println(id + ": " + map.get(id)); // NOI18N
    }
}
 
Example 15
Source File: StreamElement.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
public StreamElement(TreeMap<String, Serializable> output,DataField[] fields) {
	int nbFields = output.keySet().size();
	if(output.containsKey("timed"))
		nbFields--;
	String fieldNames[]  = new String[nbFields];
	Byte fieldTypes[]  = new Byte[nbFields];
	Serializable fieldValues[] = new Serializable[nbFields];
	TreeMap < String , Integer > indexedFieldNames = new TreeMap<String, Integer>(new CaseInsensitiveComparator());
	int idx = 0;

	long timestamp =System.currentTimeMillis();
	for (String key:output.keySet()) {
		Serializable value = output.get(key);

		if(key.equalsIgnoreCase("timed")){
			timestamp = (Long) value;
			timestampProvided=true;
		}else{ 
			fieldNames[idx] = key;
			fieldValues[idx] = value;
			for (int i=0;i<fields.length;i++) {
				if (fields[i].getName().equalsIgnoreCase(key))
					fieldTypes[idx] = fields[i].getDataTypeID();
			}
			indexedFieldNames.put(key, idx);
			idx++;
		}
	}
	this.fieldNames=fieldNames;
	this.fieldTypes=fieldTypes;
	this.fieldValues=fieldValues;
	this.indexedFieldNames=indexedFieldNames;
	this.timeStamp=timestamp;
}
 
Example 16
Source File: StringValueMapBuffer.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
public void putMap(TreeMap<Integer, String> input) {
    buffer = ByteBuffer.wrap(new byte[calculateSize(input) + getMetaDataSize()]);

    buffer.putInt(input.size());
    int position = getMetaDataSize();
    int address = position + input.size() * INTEGER_BYTES;


    for (Integer index : input.keySet()) {
        buffer.putInt(position, address);
        address = putString(address, input.get(index));
        position += INTEGER_BYTES;
    }
}
 
Example 17
Source File: LauncherModel.java    From LB-Launcher with Apache License 2.0 5 votes vote down vote up
/** Loads the workspace screens db into a map of Rank -> ScreenId */
private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
    final ContentResolver contentResolver = context.getContentResolver();
    final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
    final Cursor sc = contentResolver.query(screensUri, null, null, null, null);
    TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();

    try {
        final int idIndex = sc.getColumnIndexOrThrow(
                LauncherSettings.WorkspaceScreens._ID);
        final int rankIndex = sc.getColumnIndexOrThrow(
                LauncherSettings.WorkspaceScreens.SCREEN_RANK);
        while (sc.moveToNext()) {
            try {
                long screenId = sc.getLong(idIndex);
                int rank = sc.getInt(rankIndex);
                orderedScreens.put(rank, screenId);
            } catch (Exception e) {
                Launcher.addDumpLog(TAG, "Desktop items loading interrupted - invalid screens: " + e, true);
            }
        }
    } finally {
        sc.close();
    }

    // Log to disk
    Launcher.addDumpLog(TAG, "11683562 - loadWorkspaceScreensDb()", true);
    ArrayList<String> orderedScreensPairs= new ArrayList<String>();
    for (Integer i : orderedScreens.keySet()) {
        orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i) + " }");
    }
    Launcher.addDumpLog(TAG, "11683562 -   screens: " +
            TextUtils.join(", ", orderedScreensPairs), true);
    return orderedScreens;
}
 
Example 18
Source File: SortingData.java    From Java-Data-Analysis with MIT License 4 votes vote down vote up
public static void print(TreeMap<Integer,String> map) {
    for (Integer key : map.keySet()) {
        System.out.printf("%,12d  %-16s%n", key, map.get(key));
    }
}
 
Example 19
Source File: CLogPPredictor.java    From openchemlib-js with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public ParameterizedStringList getDetail(StereoMolecule mol) {
ParameterizedStringList detail = new ParameterizedStringList();
detail.add("cLogP Values are estimated applying an atom-type based increment system.",
					ParameterizedStringList.cStringTypeText);
detail.add("Atom-types are 64-bit numbers describing atoms and their near surrounding.",
					ParameterizedStringList.cStringTypeText);
detail.add("Recognized atom types and their contributions are:",ParameterizedStringList.cStringTypeText);

mol.normalizeAmbiguousBonds();
mol.ensureHelperArrays(Molecule.cHelperRings);

if (mol != null) {
	int errorCount = 0;
	TreeMap<Long,Integer> countMap = new TreeMap<Long,Integer>();
	NumberFormat formatter = new DecimalFormat("#0.000");
	for (int atom=0; atom<mol.getAtoms(); atom++) {
		try {
			long atomType = AtomTypeCalculator.getAtomType(mol, atom, ATOM_TYPE_MODE);
			Integer typeCount = countMap.get(new Long(atomType));
			if (typeCount == null)
				countMap.put(new Long(atomType), new Integer(1));
			else
				countMap.put(new Long(atomType), new Integer(typeCount.intValue()+1));
			}
		catch (Exception e) {
			errorCount++;
			}
		}

	if (errorCount != 0)
		detail.add("Warning: "+errorCount + " atom type(s) could not be determined.", ParameterizedStringList.cStringTypeText);

	for (Long type:countMap.keySet()) {
		if (sSortedTypeList.contains(type))
			detail.add(countMap.get(type) + " * "+
					formatter.format(INCREMENT[sSortedTypeList.getIndex(type)]) + " AtomType: 0x" + Long.toHexString(type),ParameterizedStringList.cStringTypeText);
		else
			detail.add("Warning: For atom type 0x"+Long.toHexString(type)+" ("+countMap.get(type)+" times found) is no increment available.", ParameterizedStringList.cStringTypeText);
		}
	}

return detail;
}
 
Example 20
Source File: FileManager.java    From ApexDoc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**********************************************************************************************************
 * @description generate the HTML string for the Class Menu to display on
 *              each page.
 * @param mapGroupNameToClassGroup
 *            map that holds all the Class names, and their respective Class
 *            Group.
 * @param cModels
 *            list of ClassModels
 * @return String of HTML
 */
private String getPageLinks(TreeMap<String, ClassGroup> mapGroupNameToClassGroup, ArrayList<ClassModel> cModels) {
    boolean createMiscellaneousGroup = false;

    // this is the only place we need the list of class models sorted by name.
    TreeMap<String, ClassModel> tm = new TreeMap<String, ClassModel>();
    for (ClassModel cm : cModels) {
        tm.put(cm.getClassName().toLowerCase(), cm);
        if (!createMiscellaneousGroup && cm.getClassGroup() == null)
            createMiscellaneousGroup = true;
    }
    cModels = new ArrayList<ClassModel>(tm.values());

    String links = "<td width='20%' vertical-align='top' >";
    links += "<div class='sidebar'><div class='navbar'><nav role='navigation'><ul id='mynavbar'>";
    links += "<li id='idMenuindex'><a href='.' onclick=\"gotomenu('index.html', event);return false;\" class='nav-item'>Home</a></li>";

    // add a bucket ClassGroup for all Classes without a ClassGroup specified
    if (createMiscellaneousGroup)
        mapGroupNameToClassGroup.put("Miscellaneous", new ClassGroup("Miscellaneous", null));

    // create a sorted list of ClassGroups

    for (String strGroup : mapGroupNameToClassGroup.keySet()) {
        ClassGroup cg = mapGroupNameToClassGroup.get(strGroup);
        String strGoTo = "onclick=\"gotomenu(document.location.href, event);return false;\"";
        if (cg.getContentFilename() != null)
            strGoTo = "onclick=\"gotomenu('" + cg.getContentFilename() + ".html" + "', event);return false;\"";
        links += "<li class='header' id='idMenu" + cg.getContentFilename() +
                "'><a class='nav-item nav-section-title' href='.' " +
                strGoTo + " class='nav-item'>" + strGroup + "<span class='caret'></span></a></li>";
        links += "<ul>";

        // even though this algorithm is O(n^2), it was timed at just 12
        // milliseconds, so not an issue!
        for (ClassModel cModel : cModels) {
            if (strGroup.equals(cModel.getClassGroup())
                    || (cModel.getClassGroup() == null && strGroup == "Miscellaneous")) {
                if (cModel.getNameLine() != null && cModel.getNameLine().trim().length() > 0) {
                    String fileName = cModel.getClassName();
                    links += "<li class='subitem classscope" + cModel.getScope() + "' id='idMenu" + fileName +
                            "'><a href='.' onclick=\"gotomenu('" + fileName + ".html', event);return false;\" class='nav-item sub-nav-item scope" +
                            cModel.getScope() + "'>" +
                            fileName + "</a></li>";
                }
            }
        }

        links += "</ul>";
    }

    links += "</ul></nav></div></div></div>";

    links += "</td>";
    return links;
}