List of usage examples for java.util List sort
@SuppressWarnings({ "unchecked", "rawtypes" }) default void sort(Comparator<? super E> c)
From source file:br.com.webbudget.domain.model.service.PeriodDetailService.java
/** * Metodo que busca as classes de movimentacao e seu respectivo valor * movimento, ou seja, a somatoria de todos os rateios para a aquela classe * * @param period o periodo//from w w w .jav a 2 s . c o m * @param direction qual tipo queremos, entrada ou saida * @return a lista de movimentos */ public List<MovementClass> fetchTopClassesAndValues(FinancialPeriod period, MovementClassType direction) { final List<MovementClass> withValues = new ArrayList<>(); // lista as classes sem pegar as bloqueadas final List<MovementClass> classes = this.movementClassRepository.listByTypeAndStatus(direction, Boolean.FALSE); // para cada classe pegamos o seu total em movimentacao classes.stream().forEach(clazz -> { final BigDecimal total = this.apportionmentRepository.totalMovementsPerClassAndPeriod(period, clazz); if (total != null) { clazz.setTotalMovements(total); withValues.add(clazz); } }); // ordena do maior para o menor withValues.sort((c1, c2) -> c2.getTotalMovements().compareTo(c1.getTotalMovements())); // retorna somente os 10 primeiros resultados return withValues.size() > 10 ? withValues.subList(0, 10) : withValues; }
From source file:org.eclipse.jdt.ls.core.internal.handlers.CodeActionHandler.java
/** * @param params// w w w .j av a2s .c o m * @return */ public List<Either<Command, CodeAction>> getCodeActionCommands(CodeActionParams params, IProgressMonitor monitor) { final ICompilationUnit unit = JDTUtils.resolveCompilationUnit(params.getTextDocument().getUri()); if (unit == null) { return Collections.emptyList(); } int start = DiagnosticsHelper.getStartOffset(unit, params.getRange()); int end = DiagnosticsHelper.getEndOffset(unit, params.getRange()); InnovationContext context = new InnovationContext(unit, start, end - start); context.setASTRoot(getASTRoot(unit)); IProblemLocationCore[] locations = this.getProblemLocationCores(unit, params.getContext().getDiagnostics()); List<Either<Command, CodeAction>> $ = new ArrayList<>(); List<CUCorrectionProposal> candidates = new ArrayList<>(); try { List<CUCorrectionProposal> corrections = this.quickFixProcessor.getCorrections(context, locations); candidates.addAll(corrections); } catch (CoreException e) { JavaLanguageServerPlugin.logException("Problem resolving quick fix code actions", e); } try { List<CUCorrectionProposal> corrections = this.quickAssistProcessor.getAssists(context, locations); candidates.addAll(corrections); } catch (CoreException e) { JavaLanguageServerPlugin.logException("Problem resolving quick assist code actions", e); } candidates.sort(new CUCorrectionProposalComparator()); if (params.getContext().getOnly() != null && !params.getContext().getOnly().isEmpty()) { List<CUCorrectionProposal> resultList = new ArrayList<>(); List<String> acceptedActionKinds = params.getContext().getOnly(); for (CUCorrectionProposal proposal : candidates) { if (acceptedActionKinds.contains(proposal.getKind())) { resultList.add(proposal); } } candidates = resultList; } try { for (CUCorrectionProposal proposal : candidates) { Optional<Either<Command, CodeAction>> codeActionFromProposal = getCodeActionFromProposal(proposal, params.getContext()); if (codeActionFromProposal.isPresent() && !$.contains(codeActionFromProposal.get())) { $.add(codeActionFromProposal.get()); } } } catch (CoreException e) { JavaLanguageServerPlugin.logException("Problem converting proposal to code actions", e); } // Add the source actions. $.addAll(sourceAssistProcessor.getSourceActionCommands(params, context, locations)); return $; }
From source file:org.languagetool.rules.spelling.morfologik.suggestions_ordering.SuggestionsOrderer.java
public List<String> orderSuggestionsUsingModel(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos, int wordLength) { if (!isMlAvailable()) { return suggestions; }/*from w w w . j a va2 s . co m*/ List<Pair<String, Float>> suggestionsScores = new LinkedList<>(); for (String suggestion : suggestions) { String text = sentence.getText(); String correctedSentence = text.substring(0, startPos) + suggestion + sentence.getText().substring(startPos + wordLength); float score = processRow(text, correctedSentence, word, suggestion, DEFAULT_CONTEXT_LENGTH); suggestionsScores.add(Pair.of(suggestion, score)); } Comparator<Pair<String, Float>> comparing = Comparator.comparing(Pair::getValue); suggestionsScores.sort(comparing.reversed()); List<String> result = new LinkedList<>(); suggestionsScores.iterator().forEachRemaining((Pair<String, Float> p) -> result.add(p.getKey())); return result; }
From source file:org.keycloak.models.jpa.JpaRealmProvider.java
@Override public List<GroupModel> getTopLevelGroups(RealmModel realm, Integer first, Integer max) { List<String> groupIds = em.createNamedQuery("getTopLevelGroupIds", String.class) .setParameter("realm", realm.getId()).setFirstResult(first).setMaxResults(max).getResultList(); List<GroupModel> list = new ArrayList<>(); if (Objects.nonNull(groupIds) && !groupIds.isEmpty()) { for (String id : groupIds) { GroupModel group = getGroupById(id, realm); list.add(group);/* w w w .j a v a2 s. c o m*/ } } list.sort(Comparator.comparing(GroupModel::getName)); return Collections.unmodifiableList(list); }
From source file:org.silverpeas.core.admin.domain.driver.googledriver.GoogleDirectoryRequester.java
public List<User> users() throws AdminException { try {/*from w ww. j a va 2s . c om*/ List<User> result = new LinkedList<>(); final long start = System.currentTimeMillis(); final Directory.Users.List users = getDirectoryService().users().list().setMaxResults(QUERY_MAX_RESULTS) .setCustomer(MY_CUSTOMER).setProjection("full"); String pageToken = null; while (true) { final Users currentUsers = users.setPageToken(pageToken).execute(); pageToken = currentUsers.getNextPageToken(); final List<User> currentResult = currentUsers.getUsers(); result.addAll(currentResult); if (currentResult.size() < QUERY_MAX_RESULTS || pageToken == null) { break; } } result = applyFilter(result); result.sort(Comparator.comparing((User g) -> g.getName().getFamilyName().toLowerCase()) .thenComparing(g -> g.getName().getGivenName().toLowerCase())); final long end = System.currentTimeMillis(); SilverLogger.getLogger(this).debug(() -> MessageFormat.format("Getting accounts in {0}", DurationFormatUtils.formatDurationHMS(end - start))); return result; } catch (IOException e) { throw new AdminException(e); } }
From source file:com.evolveum.midpoint.task.quartzimpl.work.workers.WorkersManager.java
public void reconcileWorkers(String coordinatorTaskOid, WorkersReconciliationOptions options, OperationResult result) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException { Task coordinatorTask = taskManager.getTask(coordinatorTaskOid, result); if (coordinatorTask.getKind() != TaskKindType.COORDINATOR) { throw new IllegalArgumentException("Task is not a coordinator task: " + coordinatorTask); }/*from www. j ava 2 s . c o m*/ List<Task> currentWorkers = new ArrayList<>(coordinatorTask.listSubtasks(true, result)); Map<WorkerKey, WorkerTasksPerNodeConfigurationType> perNodeConfigurationMap = new HashMap<>(); MultiValuedMap<String, WorkerKey> shouldBeWorkers = createWorkerKeys(coordinatorTask, perNodeConfigurationMap, result); int startingWorkersCount = currentWorkers.size(); int startingShouldBeWorkersCount = shouldBeWorkers.size(); currentWorkers.sort(Comparator.comparing(t -> { if (t.getExecutionStatus() == TaskExecutionStatus.RUNNABLE) { if (t.getNodeAsObserved() != null) { return 0; } else if (t.getNode() != null) { return 1; } else { return 2; } } else if (t.getExecutionStatus() == TaskExecutionStatus.SUSPENDED) { return 3; } else if (t.getExecutionStatus() == TaskExecutionStatus.CLOSED) { return 4; } else { return 5; } })); LOGGER.trace("Before reconciliation:\nCurrent workers: {}\nShould be workers: {}", currentWorkers, shouldBeWorkers); int matched = matchWorkers(currentWorkers, shouldBeWorkers); int renamed = renameWorkers(currentWorkers, shouldBeWorkers, result); int closedExecuting = closeExecutingWorkers(currentWorkers, result); MovedClosed movedClosed = moveWorkers(currentWorkers, shouldBeWorkers, result); int created = createWorkers(coordinatorTask, shouldBeWorkers, perNodeConfigurationMap, result); TaskWorkStateType workState = coordinatorTask.getWorkState(); Integer closedBecauseDone = null; if (isCloseWorkersOnWorkDone(options) && workState != null && Boolean.TRUE.equals(workState.isAllWorkComplete())) { closedBecauseDone = closeAllWorkers(coordinatorTask, result); } result.recordStatus(OperationResultStatus.SUCCESS, "Worker reconciliation finished. " + "Original workers: " + startingWorkersCount + ", should be: " + startingShouldBeWorkersCount + ", matched: " + matched + ", renamed: " + renamed + ", closed because executing: " + closedExecuting + ", moved: " + movedClosed.moved + ", closed because superfluous: " + movedClosed.closed + ", created: " + created + " worker task(s)." + (closedBecauseDone != null && closedBecauseDone > 0 ? " Closed " + closedBecauseDone + " workers because the work is done." : "")); }
From source file:org.phoenicis.repository.types.ClasspathRepository.java
private List<ScriptDTO> buildScripts(String typeId, String categoryId, String applicationId, String typeFileName, String categoryFileName, String applicationFileName) throws RepositoryException { try {//www .j ava 2 s . co m final String applicationScanClassPath = packagePath + "/" + typeFileName + "/" + categoryFileName + "/" + applicationFileName; Resource[] resources = resourceResolver.getResources(applicationScanClassPath + "/*"); final List<ScriptDTO> scriptDTOs = new ArrayList<>(); for (Resource resource : resources) { final String fileName = resource.getFilename(); if (!"resources".equals(fileName) && !"miniatures".equals(fileName) && !"application.json".equals(fileName)) { final ScriptDTO script = buildScript(typeId, categoryId, applicationId, typeFileName, categoryFileName, applicationFileName, fileName); scriptDTOs.add(script); } } scriptDTOs.sort(Comparator.comparing(ScriptDTO::getScriptName)); return scriptDTOs; } catch (IOException e) { throw new RepositoryException("Could not build scripts", e); } }
From source file:test.org.wildfly.swarm.microprofile.openapi.TckTestRunner.java
/** * @see org.junit.runners.ParentRunner#getChildren() *///from w w w . j av a 2s.c o m @Override protected List<ProxiedTckTest> getChildren() { List<ProxiedTckTest> children = new ArrayList<>(); Method[] methods = tckTestClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(org.testng.annotations.Test.class)) { try { ProxiedTckTest test = new ProxiedTckTest(); Object theTestObj = this.testClass.newInstance(); test.setTest(theTestObj); test.setTestMethod(method); test.setDelegate(createDelegate(theTestObj)); children.add(test); } catch (Exception e) { throw new RuntimeException(e); } } } children.sort(new Comparator<ProxiedTckTest>() { @Override public int compare(ProxiedTckTest o1, ProxiedTckTest o2) { return o1.getTestMethod().getName().compareTo(o2.getTestMethod().getName()); } }); return children; }
From source file:edu.cmu.cs.lti.discoursedb.annotation.brat.io.BratService.java
@Transactional(propagation = Propagation.REQUIRED, readOnly = true) public void exportDiscoursePart(DiscoursePart dp, String outputFolder, Boolean threaded) throws IOException { Assert.notNull(dp, "The DiscoursePart cannot be null"); Assert.hasText(outputFolder, "The outputFolder has to be specified"); //define a common base filename for all files associated with this DiscoursePart String baseFileName = discoursePart2BratName(dp); //dp.getClass().getAnnotation(Table.class).name() + "_"+dp.getId(); // delete me/*from www .j a va 2 s.co m*/ //The offset mapping keeps track of the start positions of each contribution/content in the aggregated txt file List<OffsetInfo> entityOffsetMapping = new ArrayList<>(); List<String> discoursePartText = new ArrayList<>(); List<BratAnnotation> bratAnnotations = new ArrayList<>(); BratIdGenerator bratIdGenerator = new BratIdGenerator(); int spanOffset = 0; // Sort contributions by their start time, without crashing on null List<Contribution> contribsTimeOrdered = Lists.newArrayList(contribService.findAllByDiscoursePart(dp)); //This should be (maybe, optionally) a depth-first sort, with start time as a tiebreaker. contribsTimeOrdered.sort((c1, c2) -> { if (c1 == null) { return -1; } else if (c2 == null) { return 1; } else if (c1.getStartTime() == c2.getStartTime()) { return c1.getId().compareTo(c2.getId()); } else { return c1.getStartTime().compareTo(c2.getStartTime()); } }); List<Contribution> contribs = null; if (threaded) { contribs = utilService.threadsort(contribsTimeOrdered, c -> c.getId(), c -> { Contribution p = contribService.getOneRelatedContribution(c); if (p == null) { return 0L; } else { return p.getId(); } }); } else { contribs = contribsTimeOrdered; } // Export current revision of sorted contributions for (Contribution contrib : contribs) { Content curRevision = contrib.getCurrentRevision(); String text = curRevision.getText(); String sep = new BratSeparator(0, contrib.getCurrentRevision().getAuthor().getUsername(), contrib.getCurrentRevision().getTitle(), contrib.getStartTime()).get(); discoursePartText.add(sep); discoursePartText.add(text); //annotations on content for (AnnotationInstance anno : annoService.findAnnotations(curRevision)) { bratAnnotations .addAll(convertAnnotationToBrat(anno, spanOffset, sep, text, curRevision, bratIdGenerator)); } //annotations on contributions for (AnnotationInstance anno : annoService.findAnnotations(contrib)) { bratAnnotations .addAll(convertAnnotationToBrat(anno, spanOffset, sep, text, contrib, bratIdGenerator)); } //keep track of offsets entityOffsetMapping.add(new OffsetInfo(spanOffset, contrib.getId(), curRevision.getId())); //update span offsets spanOffset += text.length() + 1; spanOffset += BratSeparator.length + 1; } if (contribs.size() > 0) { FileUtils.writeLines(new File(outputFolder, baseFileName + ".txt"), discoursePartText); FileUtils.writeLines(new File(outputFolder, baseFileName + ".ann"), bratAnnotations); FileUtils.writeLines(new File(outputFolder, baseFileName + ".offsets"), entityOffsetMapping); FileUtils.writeLines(new File(outputFolder, baseFileName + ".versions"), bratAnnotations.stream() .map(anno -> anno.getVersionInfo()).filter(Objects::nonNull).collect(Collectors.toList())); } }
From source file:org.languagetool.rules.spelling.morfologik.suggestions_ordering.SuggestionsOrdererGSoC.java
@Override public List<SuggestedReplacement> orderSuggestions(List<String> suggestions, String word, AnalyzedSentence sentence, int startPos) { if (!isMlAvailable()) { return suggestions.stream().map(SuggestedReplacement::new).collect(Collectors.toList()); }/*from w ww .j a v a 2s . co m*/ List<Pair<String, Float>> suggestionsScores = new LinkedList<>(); for (String suggestion : suggestions) { String text = sentence.getText(); String correctedSentence = text.substring(0, startPos) + suggestion + sentence.getText().substring(startPos + word.length()); float score = processRow(text, correctedSentence, word, suggestion, DEFAULT_CONTEXT_LENGTH); suggestionsScores.add(Pair.of(suggestion, score)); } Comparator<Pair<String, Float>> comparing = Comparator.comparing(Pair::getValue); suggestionsScores.sort(comparing.reversed()); return suggestionsScores.stream().map(p -> { SuggestedReplacement s = new SuggestedReplacement(p.getKey()); s.setConfidence(p.getRight()); return s; }).collect(Collectors.toList()); }