Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:org.silverpeas.web.jobstartpage.control.JobStartPagePeasSessionController.java

public ComponentInst[] getComponentsOfSpace(String spaceId) {
    ArrayList<ComponentInst> arc = getSpaceInstById(spaceId).getAllComponentsInst();
    if (arc == null || arc.isEmpty()) {
        return new ComponentInst[0];
    }/*from  www .jav  a  2s  .c  om*/
    ComponentInst[] m_Components = new ComponentInst[arc.size()];
    int j = 0;
    for (ComponentInst theComponent : arc) {
        m_Components[j++] = theComponent;
    }
    Arrays.sort(m_BrothersComponents, Comparator.comparing(ComponentInst::getOrderNum));
    return m_Components;
}

From source file:org.silverpeas.web.jobstartpage.control.JobStartPagePeasSessionController.java

public ComponentInst[] getDestBrotherComponents(String spaceId, boolean isNew, String componentId) {
    ComponentInst[] m_DestBrothersComponents;

    ArrayList<ComponentInst> arc = getSpaceInstById(spaceId).getAllComponentsInst();

    if (arc == null || arc.isEmpty()) {
        return new ComponentInst[0];
    }//from  ww w  .  j a  v  a2  s  .c o  m
    if (isNew) {
        m_DestBrothersComponents = new ComponentInst[arc.size()];
    } else {
        m_DestBrothersComponents = new ComponentInst[arc.size() - 1];
    }
    int j = 0;
    for (ComponentInst theComponent : arc) {
        if (isNew || !theComponent.getId().equals(componentId)) {
            m_DestBrothersComponents[j++] = theComponent;
        }
    }
    Arrays.sort(m_BrothersComponents, Comparator.comparing(ComponentInst::getOrderNum));
    return m_DestBrothersComponents;
}

From source file:org.eclipse.sw360.portal.portlets.projects.ProjectPortlet.java

private Function<ProjectLink, ProjectLink> filterAndSortAttachments(
        Collection<AttachmentType> attachmentTypes) {
    Predicate<Attachment> filter = att -> attachmentTypes.contains(att.getAttachmentType());
    return createProjectLinkMapper(
            rl -> rl.setAttachments(nullToEmptyList(rl.getAttachments()).stream().filter(filter)
                    .sorted(Comparator.comparing(Attachment::getCreatedTeam)
                            .thenComparing(Comparator.comparing(Attachment::getCreatedOn).reversed()))
                    .collect(Collectors.toList())));
}

From source file:org.matonto.catalog.impl.SimpleCatalogManager.java

@Override
public Commit createCommit(@Nonnull InProgressCommit inProgressCommit, Set<Commit> parents,
        @Nonnull String message) {
    IRI associatedWith = vf.createIRI(Activity.wasAssociatedWith_IRI);
    IRI informedBy = vf.createIRI(Activity.wasInformedBy_IRI);
    OffsetDateTime now = OffsetDateTime.now();
    Value user = inProgressCommit.getProperty(associatedWith).get();
    String metadata = now.toString() + user.stringValue();
    IRI generatedIRI = vf.createIRI(Activity.generated_IRI);

    if (parents != null) {
        metadata += parents.stream()//from   w  ww .  j  a v  a  2  s.  c om
                .sorted(Comparator.comparing(commit2 -> commit2.getResource().stringValue()))
                .map(commit -> commit.getResource().stringValue()).collect(Collectors.joining(""));
    }

    Commit commit = commitFactory.createNew(vf.createIRI(COMMIT_NAMESPACE + DigestUtils.shaHex(metadata)));
    commit.setProperty(inProgressCommit.getProperty(generatedIRI).get(), generatedIRI);
    commit.setProperty(vf.createLiteral(now), vf.createIRI(PROV_AT_TIME));
    commit.setProperty(vf.createLiteral(message), vf.createIRI(DCTERMS.TITLE.stringValue()));
    commit.setProperty(user, associatedWith);

    Model revisionModel = mf.createModel(inProgressCommit.getModel());
    revisionModel.remove(inProgressCommit.getResource(), null, null);
    Revision revision = revisionFactory.getExisting((Resource) inProgressCommit.getProperty(generatedIRI).get(),
            revisionModel);

    if (parents != null) {
        revision.setProperties(parents.stream().map(parent -> parent.getProperty(generatedIRI).get())
                .collect(Collectors.toSet()), vf.createIRI(Entity.wasDerivedFrom_IRI));
        commit.setProperties(parents.stream().map(Commit::getResource).collect(Collectors.toSet()), informedBy);
    }

    commit.getModel().addAll(revisionModel);
    return commit;
}

From source file:org.cgiar.ccafs.marlo.action.powb.PowbCollaborationAction.java

@Override
public void prepare() throws Exception {
    // Get current CRP
    loggedCrp = (GlobalUnit) this.getSession().get(APConstants.SESSION_CRP);
    loggedCrp = crpManager.getGlobalUnitById(loggedCrp.getId());
    Phase phase = this.getActualPhase();

    // If there is a history version being loaded
    if (this.getRequest().getParameter(APConstants.TRANSACTION_ID) != null) {
        transaction = StringUtils.trim(this.getRequest().getParameter(APConstants.TRANSACTION_ID));
        PowbSynthesis history = (PowbSynthesis) auditLogManager.getHistory(transaction);
        if (history != null) {
            powbSynthesis = history;//from  w  w w .j av a 2s  . c  o m
            powbSynthesisID = powbSynthesis.getId();
        } else {
            this.transaction = null;
            this.setTransaction("-1");
        }
    } else {
        // Get Liaison institution ID Parameter
        try {
            liaisonInstitutionID = Long.parseLong(StringUtils
                    .trim(this.getRequest().getParameter(APConstants.LIAISON_INSTITUTION_REQUEST_ID)));
        } catch (NumberFormatException e) {
            User user = userManager.getUser(this.getCurrentUser().getId());
            if (user.getLiasonsUsers() != null || !user.getLiasonsUsers().isEmpty()) {
                List<LiaisonUser> liaisonUsers = new ArrayList<>(user.getLiasonsUsers().stream()
                        .filter(lu -> lu.isActive() && lu.getLiaisonInstitution().isActive()
                                && lu.getLiaisonInstitution().getCrp().getId() == loggedCrp.getId()
                                && lu.getLiaisonInstitution().getInstitution() == null)
                        .collect(Collectors.toList()));
                if (!liaisonUsers.isEmpty()) {
                    boolean isLeader = false;
                    for (LiaisonUser liaisonUser : liaisonUsers) {
                        LiaisonInstitution institution = liaisonUser.getLiaisonInstitution();
                        if (institution.isActive()) {
                            if (institution.getCrpProgram() != null) {
                                if (institution.getCrpProgram()
                                        .getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue()) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            } else {
                                if (institution.getAcronym().equals("PMU")) {
                                    liaisonInstitutionID = institution.getId();
                                    isLeader = true;
                                    break;
                                }
                            }
                        }
                    }
                    if (!isLeader) {
                        liaisonInstitutionID = this.firstFlagship();
                    }
                } else {
                    liaisonInstitutionID = this.firstFlagship();
                }
            } else {
                liaisonInstitutionID = this.firstFlagship();
            }
        }

        try {
            powbSynthesisID = Long
                    .parseLong(StringUtils.trim(this.getRequest().getParameter(APConstants.POWB_SYNTHESIS_ID)));
            powbSynthesis = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID);

            if (!powbSynthesis.getPhase().equals(phase)) {
                powbSynthesis = powbSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
                if (powbSynthesis == null) {
                    powbSynthesis = this.createPowbSynthesis(phase.getId(), liaisonInstitutionID);
                }
                powbSynthesisID = powbSynthesis.getId();
            }
        } catch (Exception e) {

            powbSynthesis = powbSynthesisManager.findSynthesis(phase.getId(), liaisonInstitutionID);
            if (powbSynthesis == null) {
                powbSynthesis = this.createPowbSynthesis(phase.getId(), liaisonInstitutionID);
            }
            powbSynthesisID = powbSynthesis.getId();

        }
    }

    if (powbSynthesis != null) {

        PowbSynthesis powbSynthesisDB = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID);
        powbSynthesisID = powbSynthesisDB.getId();
        liaisonInstitutionID = powbSynthesisDB.getLiaisonInstitution().getId();
        liaisonInstitution = liaisonInstitutionManager.getLiaisonInstitutionById(liaisonInstitutionID);

        Path path = this.getAutoSaveFilePath();
        // Verify if there is a Draft file
        if (path.toFile().exists() && this.getCurrentUser().isAutoSave()) {
            BufferedReader reader;
            reader = new BufferedReader(new FileReader(path.toFile()));
            Gson gson = new GsonBuilder().create();
            JsonObject jReader = gson.fromJson(reader, JsonObject.class);
            AutoSaveReader autoSaveReader = new AutoSaveReader();
            powbSynthesis = (PowbSynthesis) autoSaveReader.readFromJson(jReader);
            powbSynthesisID = powbSynthesis.getId();
            if (powbSynthesis.getPowbCollaborationGlobalUnitsList() != null) {
                for (PowbCollaborationGlobalUnit powbCollaborationGlobalUnit : powbSynthesis
                        .getPowbCollaborationGlobalUnitsList()) {
                    if (powbCollaborationGlobalUnit.getGlobalUnit() != null
                            && powbCollaborationGlobalUnit.getGlobalUnit().getId() != -1) {
                        powbCollaborationGlobalUnit.setGlobalUnit(crpManager
                                .getGlobalUnitById(powbCollaborationGlobalUnit.getGlobalUnit().getId()));
                    }
                }
            }
            if (powbSynthesis.getRegions() != null) {
                for (PowbCollaborationRegion powbCollaborationRegion : powbSynthesis.getRegions()) {
                    if (powbCollaborationRegion.getLiaisonInstitution() != null
                            && powbCollaborationRegion.getLiaisonInstitution().getId() != -1) {
                        powbCollaborationRegion
                                .setLiaisonInstitution(liaisonInstitutionManager.getLiaisonInstitutionById(
                                        powbCollaborationRegion.getLiaisonInstitution().getId()));
                    }
                }
                powbSynthesis.getRegions().sort((p1, p2) -> p1.getLiaisonInstitution().getAcronym()
                        .compareTo(p2.getLiaisonInstitution().getAcronym()));
            }
            this.setDraft(true);
            reader.close();
        } else {
            this.setDraft(false);
            // Check if ToC relation is null -create it
            if (powbSynthesis.getCollaboration() == null) {
                PowbCollaboration powbCollaboration = new PowbCollaboration();
                // create one to one relation
                powbSynthesis.setCollaboration(powbCollaboration);
                powbCollaboration.setPowbSynthesis(powbSynthesis);
                // save the changes
                powbSynthesis = powbSynthesisManager.savePowbSynthesis(powbSynthesis);
            }
            powbSynthesis.setPowbCollaborationGlobalUnitsList(powbSynthesis.getPowbCollaborationGlobalUnits()
                    .stream().filter(c -> c.isActive()).collect(Collectors.toList()));

            powbSynthesis.setRegions(powbSynthesis.getPowbCollaborationRegions().stream()
                    .filter(c -> c.isActive()).collect(Collectors.toList()));

            powbSynthesis.getRegions().sort((p1, p2) -> p1.getLiaisonInstitution().getAcronym()
                    .compareTo(p2.getLiaisonInstitution().getAcronym()));
        }
    }

    if (this.isPMU()) {
        // this.loadLocations();
        crpPrograms = loggedCrp.getCrpPrograms().stream()
                .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
                .collect(Collectors.toList());
        for (CrpProgram crpProgram : crpPrograms) {
            List<LiaisonInstitution> liaisonInstitutions = crpProgram.getLiaisonInstitutions().stream()
                    .filter(c -> c.isActive()).collect(Collectors.toList());
            if (!liaisonInstitutions.isEmpty()) {
                PowbSynthesis powbSynthesisProgram = powbSynthesisManager.findSynthesis(phase.getId(),
                        liaisonInstitutions.get(0).getId());
                if (powbSynthesisProgram != null) {
                    powbSynthesisProgram.setPowbCollaborationGlobalUnitsList(
                            powbSynthesisProgram.getPowbCollaborationGlobalUnits().stream()
                                    .filter(c -> c.isActive()).collect(Collectors.toList()));

                    crpProgram.setCollaboration(powbSynthesisProgram.getCollaboration());
                    crpProgram.setSynthesis(powbSynthesisProgram);

                }
            }
            if (crpProgram.getSynthesis() == null) {
                crpProgram.setSynthesis(new PowbSynthesis());
            }
            if (crpProgram.getCollaboration() == null) {
                crpProgram.setCollaboration(new PowbCollaboration());

            }

        }
        crpPrograms.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym()));
    }
    if (this.hasSpecificities(APConstants.CRP_HAS_REGIONS)) {
        regions = liaisonInstitutionManager.findAll().stream()
                .filter(c -> c.isActive() && c.getCrpProgram() != null
                        && c.getCrpProgram().getProgramType() == ProgramType.REGIONAL_PROGRAM_TYPE.getValue())
                .collect(Collectors.toList());
        regions.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym()));
    } else {
        regions = new ArrayList<>();
    }
    globalUnits = new ArrayList<>();
    List<GlobalUnit> globalUnitsList = crpManager.findAll().stream()
            .filter(c -> c.isActive() && c.getGlobalUnitType().getId() != 2).collect(Collectors.toList());

    for (GlobalUnit globalUnit : globalUnitsList) {
        if (!globalUnit.getId().equals(loggedCrp.getId())) {
            if (globalUnit.getAcronym() != null && globalUnit.getAcronym().trim().length() == 0) {
                globalUnit.setAcronymValid(globalUnit.getName());
            } else {
                globalUnit.setAcronymValid(globalUnit.getAcronym());

            }
            globalUnits.add(globalUnit);
        }

    }
    globalUnits.sort((p1, p2) -> p1.getAcronymValid().compareTo(p2.getAcronymValid()));
    globalUnits.sort((p1, p2) -> {
        if (p1.getGlobalUnitType().getId().compareTo(p2.getGlobalUnitType().getId()) == 0) {
            return p1.getAcronymValid().compareTo(p2.getAcronymValid());

        } else {
            return p1.getGlobalUnitType().getId().compareTo(p2.getGlobalUnitType().getId());
        }
    });

    // Get the list of liaison institutions Flagships and PMU.
    liaisonInstitutions = loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() != null && c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
            .collect(Collectors.toList());
    liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym));

    liaisonInstitutions.addAll(loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() == null && c.isActive() && c.getAcronym().equals("PMU"))
            .collect(Collectors.toList()));

    powbSynthesisBD = powbSynthesisManager.getPowbSynthesisById(powbSynthesisID);

    // Base Permission
    String params[] = { loggedCrp.getAcronym(), powbSynthesis.getId() + "" };
    this.setBasePermission(this.getText(Permission.POWB_SYNTHESIS_COLLABORATION_BASE_PERMISSION, params));

    if (this.isHttpPost()) {
        if (powbSynthesis.getPowbCollaborationGlobalUnitsList() != null) {
            powbSynthesis.getPowbCollaborationGlobalUnitsList().clear();
        }
        if (powbSynthesis.getRegions() != null) {
            powbSynthesis.getRegions().clear();
        }
    }
}

From source file:de.fosd.jdime.matcher.cost_model.CostModelMatcher.java

/**
 * Proposes a new set of <code>CMMatching</code>s based on the previous matchings <code>m</code>.
 *
 * @param m//from  www  . j  a va 2  s.com
 *         the matchings from the previous iteration
 * @param preFixed
 *         the matchings between the left and right tree that are fixed
 * @return the proposed matchings for the next iteration
 */
private CMMatchings<T> propose(CMMatchings<T> m, CMMatchings<T> preFixed, CMParameters<T> parameters) {
    CMMatchings<T> mVariable = new CMMatchings<>(m, m.left, m.right);
    mVariable.removeAll(preFixed);

    int j;

    if (parameters.fixRandomPercentage) {
        int lower = (int) (parameters.fixLower * mVariable.size());
        int upper = (int) (parameters.fixUpper * mVariable.size());

        Collections.shuffle(mVariable, parameters.rng); // TODO a switch to turn this off
        j = intFromRange(lower, upper, parameters);
    } else {
        //TODO sort by exact cost?
        mVariable.sort(Comparator.comparing(CMMatching::getExactCost));
        j = parameters.rng.nextInt(mVariable.size());
    }

    CMMatchings<T> fixed = new CMMatchings<>(mVariable.subList(0, j), m.left, m.right);

    log(FINER, m, () -> "Fixing the first " + j + "variable matchings from the last iteration.");
    log(FINEST, m, () -> "They are: " + fixed);

    fixed.addAll(preFixed);

    CMMatchings<T> proposition = complete(fixed, parameters);

    log(FINER, proposition, () -> "Proposing matchings for the next iteration.");
    log(FINEST, proposition, () -> "Proposition is: " + proposition);

    return proposition;
}

From source file:com.haulmont.cuba.gui.components.filter.FilterDelegateImpl.java

protected void addFiltersPopupActions() {
    addResetFilterAction(filtersPopupButton);

    filterEntities.sort(Comparator.comparing(this::getFilterCaption));

    Iterator<FilterEntity> it = filterEntities.iterator();
    int addedEntitiesCount = 0;
    while (it.hasNext() && addedEntitiesCount < clientConfig.getGenericFilterPopupListSize()) {
        final FilterEntity fe = it.next();
        addSetFilterEntityAction(filtersPopupButton, fe);
        addedEntitiesCount++;// w  ww. j a va2  s  . co  m
    }

    if (filterEntities.size() > clientConfig.getGenericFilterPopupListSize()) {
        addShowMoreFilterEntitiesAction(filtersPopupButton);
    }
}

From source file:org.kuali.kra.award.home.Award.java

public void add(AwardCloseout awardCloseoutItem) {
    awardCloseoutNewItems.clear();/* w ww. jav  a 2 s  .c om*/
    if (awardCloseoutItems != null && awardCloseoutItems.size() > TOTAL_STATIC_REPORTS) {
        for (int i = TOTAL_STATIC_REPORTS; i < awardCloseoutItems.size(); i++) {
            awardCloseoutNewItems.add(awardCloseoutItems.get(i));
        }
    }
    awardCloseoutItems.removeAll(awardCloseoutNewItems);
    awardCloseoutNewItems.add(awardCloseoutItem);
    Collections.sort(awardCloseoutNewItems, Comparator.comparing(AwardCloseout::getCloseoutReportName));
    awardCloseoutItems.addAll(awardCloseoutNewItems);
    awardCloseoutItem.setAward(this);
}

From source file:org.onosproject.t3.impl.TroubleshootManager.java

/**
 * Finds the flow entry with the minimun next table Id.
 *
 * @param deviceId  the device to search
 * @param currentId the current id. the search will use this as minimum
 * @return the flow entry with the minimum table Id after the given one.
 *///from w ww  .  ja va  2s  . co m
private FlowEntry findNextTableIdEntry(DeviceId deviceId, int currentId) {

    final Comparator<FlowEntry> comparator = Comparator
            .comparing((FlowEntry f) -> ((IndexTableId) f.table()).id());

    return Lists
            .newArrayList(
                    flowRuleService.getFlowEntriesByState(deviceId, FlowEntry.FlowEntryState.ADDED).iterator())
            .stream().filter(f -> ((IndexTableId) f.table()).id() > currentId).min(comparator).orElse(null);
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

public String getLastPaymentPaidFinYear(final Advertisement advertisement) {
    String paidUptoFinYearDesc = EMPTY;
    if (advertisement != null && advertisement.getDemandId() != null) {
        List<EgDemandDetails> demandDetailsList = advertisement.getDemandId().getEgDemandDetails().stream()
                .sorted(Comparator.comparing(EgDemandDetails::getModifiedDate).reversed())
                .filter(demandDtl -> demandDtl.getAmtCollected().compareTo(BigDecimal.ZERO) > 0)
                .collect(Collectors.toList());
        if (!demandDetailsList.isEmpty())
            paidUptoFinYearDesc = getInsatllmentByModuleForGivenDate(demandDetailsList.get(0).getModifiedDate())
                    .getDescription();/*from   w  w  w . j  av  a2s  .c  o m*/
        else
            paidUptoFinYearDesc = "No Payment Done Yet";
    }
    return paidUptoFinYearDesc;
}