List of usage examples for java.util TreeSet addAll
public boolean addAll(Collection<? extends E> c)
From source file:com.hichinaschool.flashcards.libanki.Sched.java
private TreeSet<Object[]> _groupChildrenMain(TreeSet<Object[]> grps, int depth) { TreeSet<Object[]> tree = new TreeSet<Object[]>(new DeckNameCompare()); // group and recurse Iterator<Object[]> it = grps.iterator(); Object[] tmp = null;/*w ww . j a va2s . c o m*/ while (tmp != null || it.hasNext()) { Object[] head; if (tmp != null) { head = tmp; tmp = null; } else { head = it.next(); } String[] title = (String[]) head[0]; long did = (Long) head[1]; int newCount = (Integer) head[2]; int lrnCount = (Integer) head[3]; int revCount = (Integer) head[4]; TreeSet<Object[]> children = new TreeSet<Object[]>(new DeckNameCompare()); while (it.hasNext()) { Object[] o = it.next(); if (((String[]) o[0])[depth].equals(title[depth])) { // add to children children.add(o); } else { // proceed with this as head tmp = o; break; } } children = _groupChildrenMain(children, depth + 1); // tally up children counts, but skip deeper sub-decks for (Object[] ch : children) { if (((String[]) ch[0]).length == ((String[]) head[0]).length + 1) { newCount += (Integer) ch[2]; lrnCount += (Integer) ch[3]; revCount += (Integer) ch[4]; } } // limit the counts to the deck's limits JSONObject conf = mCol.getDecks().confForDid(did); JSONObject deck = mCol.getDecks().get(did); try { if (conf.getInt("dyn") == 0) { revCount = Math.max(0, Math.min(revCount, conf.getJSONObject("rev").getInt("perDay") - deck.getJSONArray("revToday").getInt(1))); newCount = Math.max(0, Math.min(newCount, conf.getJSONObject("new").getInt("perDay") - deck.getJSONArray("newToday").getInt(1))); } } catch (JSONException e) { throw new RuntimeException(e); } tree.add(new Object[] { title, did, newCount, lrnCount, revCount, children }); } TreeSet<Object[]> result = new TreeSet<Object[]>(new DeckNameCompare()); for (Object[] t : tree) { result.add(new Object[] { t[0], t[1], t[2], t[3], t[4] }); result.addAll((TreeSet<Object[]>) t[5]); } return result; }
From source file:module.siadap.domain.wrappers.UnitSiadapWrapper.java
public Set<PersonSiadapWrapper> getPeopleHarmonizedInThisUnit(boolean descendOnStructure) { TreeSet<PersonSiadapWrapper> personsToReturn = new TreeSet<PersonSiadapWrapper>( PersonSiadapWrapper.PERSON_COMPARATOR_BY_NAME_FALLBACK_YEAR_THEN_PERSON_OID); SiadapYearConfiguration configuration = getConfiguration(); List<Person> childPersons = getChildPersons(configuration.getSiadap3HarmonizationRelation(), configuration.getSiadap2HarmonizationRelation()); if (descendOnStructure) { for (Unit childUnit : getChildUnits(configuration.getHarmonizationUnitRelations())) { personsToReturn.addAll(new UnitSiadapWrapper(childUnit, configuration.getYear()) .getPeopleHarmonizedInThisUnit(true)); }/* ww w . j a va2 s . c om*/ } personsToReturn.addAll(Collections2.transform(childPersons, new Function<Person, PersonSiadapWrapper>() { @Override public PersonSiadapWrapper apply(Person input) { if (input == null) { return null; } return new PersonSiadapWrapper(input, getYear()); } })); return personsToReturn; }
From source file:org.apache.hadoop.hbase.regionserver.HRegionServer.java
public String[] getRegionServerCoprocessors() { TreeSet<String> coprocessors = new TreeSet<String>(this.hlog.getCoprocessorHost().getCoprocessors()); Collection<HRegion> regions = getOnlineRegionsLocalContext(); for (HRegion region : regions) { coprocessors.addAll(region.getCoprocessorHost().getCoprocessors()); }/*w ww . j a v a 2 s . c o m*/ return coprocessors.toArray(new String[coprocessors.size()]); }
From source file:net.sourceforge.fenixedu.domain.ExecutionCourse.java
public SortedSet<BibliographicReference> getOrderedBibliographicReferences() { TreeSet<BibliographicReference> references = new TreeSet<BibliographicReference>( BibliographicReference.COMPARATOR_BY_ORDER); references.addAll(getAssociatedBibliographicReferencesSet()); return references; }
From source file:org.apache.storm.scheduler.resource.strategies.scheduling.DefaultResourceAwareStrategy.java
/** * Sort objects by the following two criteria. 1) the number executors of the topology that needs to be scheduled is already on the object (node or rack) in descending order. * The reasoning to sort based on criterion 1 is so we schedule the rest of a topology on the same object (node or rack) as the existing executors of the topology. * 2) the subordinate/subservient resource availability percentage of a rack in descending order * We calculate the resource availability percentage by dividing the resource availability of the object (node or rack) by the resource availability of the entire rack or cluster depending on if object * references a node or a rack./*from w ww.j a v a 2s . c o m*/ * By doing this calculation, objects (node or rack) that have exhausted or little of one of the resources mentioned above will be ranked after racks that have more balanced resource availability. * So we will be less likely to pick a rack that have a lot of one resource but a low amount of another. * * @param allResources contains all individual ObjectResources as well as cumulative stats * @param existingScheduleFunc a function to get existing executors already scheduled on this object * @return a sorted list of ObjectResources */ private TreeSet<ObjectResources> sortObjectResources(final AllResources allResources, final ExistingScheduleFunc existingScheduleFunc) { for (ObjectResources objectResources : allResources.objectResources) { StringBuilder sb = new StringBuilder(); if (allResources.availCpuResourcesOverall <= 0.0 || allResources.availMemResourcesOverall <= 0.0) { objectResources.effectiveResources = 0.0; } else { List<Double> values = new LinkedList<Double>(); //add cpu double cpuPercent = (objectResources.availCpu / allResources.availCpuResourcesOverall) * 100.0; values.add(cpuPercent); sb.append(String.format("CPU %f(%f%%) ", objectResources.availCpu, cpuPercent)); //add memory double memoryPercent = (objectResources.availMem / allResources.availMemResourcesOverall) * 100.0; values.add(memoryPercent); sb.append(String.format("MEM %f(%f%%) ", objectResources.availMem, memoryPercent)); objectResources.effectiveResources = Collections.min(values); } LOG.debug("{}: Avail [ {} ] Total [ CPU {} MEM {}] effective resources: {}", objectResources.id, sb.toString(), objectResources.totalCpu, objectResources.totalMem, objectResources.effectiveResources); } TreeSet<ObjectResources> sortedObjectResources = new TreeSet<ObjectResources>( new Comparator<ObjectResources>() { @Override public int compare(ObjectResources o1, ObjectResources o2) { int execsScheduled1 = existingScheduleFunc.getNumExistingSchedule(o1.id); int execsScheduled2 = existingScheduleFunc.getNumExistingSchedule(o2.id); if (execsScheduled1 > execsScheduled2) { return -1; } else if (execsScheduled1 < execsScheduled2) { return 1; } else { if (o1.effectiveResources > o2.effectiveResources) { return -1; } else if (o1.effectiveResources < o2.effectiveResources) { return 1; } else { List<Double> o1_values = new LinkedList<Double>(); List<Double> o2_values = new LinkedList<Double>(); o1_values.add((o1.availCpu / allResources.availCpuResourcesOverall) * 100.0); o2_values.add((o2.availCpu / allResources.availCpuResourcesOverall) * 100.0); o1_values.add((o1.availMem / allResources.availMemResourcesOverall) * 100.0); o2_values.add((o2.availMem / allResources.availMemResourcesOverall) * 100.0); double o1_avg = ResourceUtils.avg(o1_values); double o2_avg = ResourceUtils.avg(o2_values); if (o1_avg > o2_avg) { return -1; } else if (o1_avg < o2_avg) { return 1; } else { return o1.id.compareTo(o2.id); } } } } }); sortedObjectResources.addAll(allResources.objectResources); LOG.debug("Sorted Object Resources: {}", sortedObjectResources); return sortedObjectResources; }
From source file:org.alfresco.repo.site.SiteServiceImpl.java
public PagingResults<SiteMembership> listSitesPaged(final String userName, List<Pair<SiteService.SortFields, Boolean>> sortProps, final PagingRequest pagingRequest) { List<SiteMembership> siteMembers = listSiteMemberships(userName, 0); final int totalSize = siteMembers.size(); final PageDetails pageDetails = PageDetails.getPageDetails(pagingRequest, totalSize); final List<SiteMembership> resultList; if (sortProps == null) { resultList = siteMembers;/*from w w w.j ava 2 s .c o m*/ } else { List<Pair<? extends Object, SortOrder>> sortPairs = new ArrayList<Pair<? extends Object, SortOrder>>( sortProps.size()); for (Pair<SiteService.SortFields, Boolean> sortProp : sortProps) { sortPairs.add(new Pair<SiteService.SortFields, SortOrder>(sortProp.getFirst(), (sortProp.getSecond() ? SortOrder.ASCENDING : SortOrder.DESCENDING))); } TreeSet<SiteMembership> sortedSet = new TreeSet<SiteMembership>( new SiteMembershipComparator(sortPairs, SiteMembershipComparator.Type.SITES)); sortedSet.addAll(siteMembers); resultList = new ArrayList<SiteMembership>(sortedSet); } PagingResults<SiteMembership> res = new PagingResults<SiteMembership>() { @Override public boolean hasMoreItems() { return pageDetails.hasMoreItems(); } @Override public Pair<Integer, Integer> getTotalResultCount() { Integer size = totalSize; return new Pair<Integer, Integer>(size, size); } @Override public String getQueryExecutionId() { return GUID.generate(); } @Override public List<SiteMembership> getPage() { return resultList; } }; return res; }
From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java
/** * The contextPackages may declare overrides. * Example:/* w ww . ja v a2s. c o m*/ * "com.A" * "com.B" * "com.C" * "@com.A" <-- Indicates a reference to a class (versus ns 2 pkg conversion) * "com.A > com.B" <-- This says com.A overrides com.B * * This method prunes the overrides and overriden packages. * Example return: * "com.A" * "com.C" * @param contextPackages * @return List<String> class references */ protected static List<String> pruneDirectives(TreeSet<String> contextPackages) { List<String> removePkgsList = new ArrayList<String>(); List<String> strongPkgsList = new ArrayList<String>(); List<String> classRefs = new ArrayList<String>(); // Walk the contextPackages looking for entries representing directives Iterator<String> it = contextPackages.iterator(); while (it.hasNext()) { String entry = it.next(); // If the entry contains an override character if (entry.contains(">")) { if (log.isDebugEnabled()) { log.debug("Override found:" + entry); } // Remove the entry using an iterator remove() it.remove(); // Store the overridden package String removePkg = entry.substring(entry.indexOf(">") + 1); removePkg = removePkg.trim(); removePkgsList.add(removePkg); } if (entry.startsWith("@")) { if (log.isDebugEnabled()) { log.debug("Strong (class) reference found:" + entry); } // Remove the entry using an iterator remove() it.remove(); // Store the overridden package String strongPkg = entry.substring(1); strongPkg = strongPkg.trim(); strongPkgsList.add(strongPkg); } if (entry.startsWith("[")) { if (log.isDebugEnabled()) { log.debug("Class Reference found:" + entry); } // Remove the entry using an iterator remove() it.remove(); // Store the class String cls = entry.substring(1, entry.length() - 1); classRefs.add(cls); } } // Now walk the contextPackages and remove the overriden packages it = contextPackages.iterator(); while (it.hasNext()) { String entry = it.next(); // If the entry contains an override character if (removePkgsList.contains(entry)) { if (log.isDebugEnabled()) { log.debug("Removing override package:" + entry); } // Remove the overridden package using an iterator remove() it.remove(); } } // Now add back all of the strong packages contextPackages.addAll(strongPkgsList); return classRefs; }
From source file:pcgen.io.PCGVer2Creator.java
private void appendTempBonuses(StringBuilder buffer) { final List<String> trackList = new ArrayList<>(); TreeSet<Map.Entry<BonusObj, BonusManager.TempBonusInfo>> sortedbonus = new TreeSet<>( (a, b) -> {/*from w ww. j av a2 s .c om*/ BonusObj keyA = a.getKey(); BonusObj keyB = b.getKey(); if (!keyA.getBonusName().equals(keyB.getBonusName())) { return keyA.getBonusName().compareTo(keyB.getBonusName()); } if (!keyA.getBonusInfo().equals(keyB.getBonusInfo())) { return keyA.getBonusInfo().compareTo(keyB.getBonusInfo()); } return keyA.getPCCText().compareTo(keyB.getPCCText()); }); sortedbonus.addAll(thePC.getTempBonusMap().entrySet()); //for (BonusManager.TempBonusInfo tbi : thePC.getTempBonusMap().values()) for (Map.Entry<BonusObj, BonusManager.TempBonusInfo> me : sortedbonus) { BonusObj bonus = me.getKey(); TempBonusInfo tbi = me.getValue(); Object creObj = tbi.source; Object tarObj = tbi.target; final String outString = tempBonusName(creObj, tarObj); if (trackList.contains(outString)) { continue; } trackList.add(outString); buffer.append(outString); String bonusName = BonusDisplay.getBonusDisplayName(tbi); if (thePC.getTempBonusFilters().contains(bonusName)) { buffer.append('|'); buffer.append(IOConstants.TAG_TEMPBONUSACTIVE).append(":N"); } /* * Why do we loop through the bonuses again? It is looped through * again so that only items associated with this source (e.g. * Template and Target object) are written, but that ALL of the * items are written on one line. */ for (Map.Entry<BonusObj, BonusManager.TempBonusInfo> subme : sortedbonus) { BonusObj subBonus = subme.getKey(); TempBonusInfo subtbi = subme.getValue(); Object cObj = subtbi.source; Object tObj = subtbi.target; final String inString = tempBonusName(cObj, tObj); if (inString.equals(outString)) { buffer.append('|'); buffer.append(IOConstants.TAG_TEMPBONUSBONUS).append(':'); buffer.append(EntityEncoder.encode(subBonus.getPCCText())); } } buffer.append(IOConstants.LINE_SEP); } }
From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.GetEngine.java
/** * Prepare the results returned from the server for processing in the main * get loop.//w w w . ja va2s . co m * */ private GetOperation[] prepareGetOperations(final AsyncGetOperation asyncOp, final GetOperation[][] results) { Check.notNull(asyncOp, "asyncOp"); //$NON-NLS-1$ Check.notNull(results, "results"); //$NON-NLS-1$ /* * The common case is a single result, and we do not want to slow that * down. In the case where there are multiple requests (and thus * multiple results), we need to filter to make sure that we don't have * redundant getOps. */ Map<String, GetOperation> newLocalItemHash = null; if (results.length > 1) { newLocalItemHash = new TreeMap<String, GetOperation>(LocalPath.TOP_DOWN_COMPARATOR); } System.currentTimeMillis(); for (int i = 0; i < results.length; i++) { final GetOperation[] tempGetOps = results[i]; for (final GetOperation getOp : tempGetOps) { /* * We need to build a hashtable of getOps that have a source * that is an existing item. In the multiple result case, we * also need to filter out redundant getOps. Each local item * currently on disk can only have one operation. Also, each * target local item can have only one operation. They must be * considered separately. */ final String sourceLocalItem = getOp.getSourceLocalItem(); if (sourceLocalItem != null) { if (results.length == 1) { if (!asyncOp.getExistingLocalHash().containsKey(sourceLocalItem)) { asyncOp.getExistingLocalHash().put(sourceLocalItem, getOp); } else { // This is a server problem. onNonFatalError(new Exception(MessageFormat.format( //@formatter:off Messages.getString( "GetEngine.ServerGateUsTwoGetOperationsForSameLocalPathMayRequireMultipleGetsFormat"), //$NON-NLS-1$ //@formatter:on sourceLocalItem))); } } else { // I think this test is redundant because of the test // above if (sourceLocalItem != null) { if (!asyncOp.getExistingLocalHash().containsKey(sourceLocalItem)) { asyncOp.getExistingLocalHash().put(sourceLocalItem, getOp); } else { final GetOperation existingOp = asyncOp.getExistingLocalHash().get(sourceLocalItem); /* * favor the get operation which has a target * local item this happens in the case when the * caller does 2 scoped gets See bug 416603 for * details */ if (existingOp.getTargetLocalItem() == null && getOp.getTargetLocalItem() != null) { asyncOp.getExistingLocalHash().put(sourceLocalItem, getOp); } } } } } else if (results.length != 1) { final String newLocalItem = getOp.getTargetLocalItem(); if (newLocalItem != null && !newLocalItemHash.containsKey(newLocalItem)) { newLocalItemHash.put(newLocalItem, getOp); } } } } /* * Since JDK 1.7 {@link Arrays.sort} algorithm has changed: * * The implementation was adapted from Tim Peters's list sort for Python * (<a href= * "http://svn.python.org/projects/python/trunk/Objects/listsort.txt"> * TimSort</a>). It uses techiques from Peter McIlroy's "Optimistic * Sorting and Information Theoretic Complexity", in Proceedings of the * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. * * For some unknown reason the new implementation is not compatible with * the {@link GetOperation}'s compareTo method. We have to use another * means to get an ordered list of operation, e.g. to utilize {@link * TreeSet}. */ // Sort the get operations for execution. Note that HatGui's cache // model relies on this. final TreeSet<GetOperation> getOps = new TreeSet<GetOperation>(GetOperation.GET_OPERATION_COMPARATOR); // Again, we've optimized the case of a single result. if (results.length == 1) { getOps.addAll(Arrays.asList(results[0])); } else { // copy our get ops to the output sorted set getOps.addAll(asyncOp.getExistingLocalHash().values()); getOps.addAll(newLocalItemHash.values()); } // Record the total number of operations for use in the events. asyncOp.totalNumOperations = getOps.size(); return getOps.toArray(new GetOperation[getOps.size()]); }
From source file:net.sourceforge.fenixedu.domain.StudentCurricularPlan.java
final public Enrolment getLatestDissertationEnrolment() { final TreeSet<Enrolment> result = new TreeSet<Enrolment>(Enrolment.COMPARATOR_BY_EXECUTION_PERIOD_AND_ID); result.addAll(getDissertationEnrolments()); return result.isEmpty() ? null : result.last(); }