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.sleuthkit.autopsy.timeline.db.EventDB.java

/**
 * merge the events in the given list if they are within the same period
 * General algorithm is as follows:/*from   www  .ja v a2 s  . c  o m*/
 *
 * 1) sort them into a map from (type, description)-> List<aggevent>
 * 2) for each key in map, merge the events and accumulate them in a list to
 * return
 *
 * @param timeUnitLength
 * @param preMergedEvents
 *
 * @return
 */
static private List<EventStripe> mergeClustersToStripes(Period timeUnitLength,
        List<EventCluster> preMergedEvents) {

    //effectively map from type to (map from description to events)
    Map<EventType, SetMultimap<String, EventCluster>> typeMap = new HashMap<>();

    for (EventCluster aggregateEvent : preMergedEvents) {
        typeMap.computeIfAbsent(aggregateEvent.getEventType(), eventType -> HashMultimap.create())
                .put(aggregateEvent.getDescription(), aggregateEvent);
    }
    //result list to return
    ArrayList<EventCluster> aggEvents = new ArrayList<>();

    //For each (type, description) key, merge agg events
    for (SetMultimap<String, EventCluster> descrMap : typeMap.values()) {
        //for each description ...
        for (String descr : descrMap.keySet()) {
            //run through the sorted events, merging together adjacent events
            Iterator<EventCluster> iterator = descrMap.get(descr).stream()
                    .sorted(Comparator.comparing(event -> event.getSpan().getStartMillis())).iterator();
            EventCluster current = iterator.next();
            while (iterator.hasNext()) {
                EventCluster next = iterator.next();
                Interval gap = current.getSpan().gap(next.getSpan());

                //if they overlap or gap is less one quarter timeUnitLength
                //TODO: 1/4 factor is arbitrary. review! -jm
                if (gap == null || gap.toDuration()
                        .getMillis() <= timeUnitLength.toDurationFrom(gap.getStart()).getMillis() / 4) {
                    //merge them
                    current = EventCluster.merge(current, next);
                } else {
                    //done merging into current, set next as new current
                    aggEvents.add(current);
                    current = next;
                }
            }
            aggEvents.add(current);
        }
    }

    //merge clusters to stripes
    Map<ImmutablePair<EventType, String>, EventStripe> stripeDescMap = new HashMap<>();

    for (EventCluster eventCluster : aggEvents) {
        stripeDescMap.merge(ImmutablePair.of(eventCluster.getEventType(), eventCluster.getDescription()),
                new EventStripe(eventCluster), EventStripe::merge);
    }

    return stripeDescMap.values().stream().sorted(Comparator.comparing(EventStripe::getStartMillis))
            .collect(Collectors.toList());
}

From source file:org.matonto.catalog.rest.impl.CatalogRestImpl.java

/**
 * Creates a Response for a page of a sorted limited offset Set of Things based on the return type of the passed
 * function using the passed full Set of Resources.
 *
 * @param uriInfo The URI information of the request.
 * @param iris The Set of Resource for all of the Things.
 * @param thingFunction A Function to retrieve Things based on their Resource IDs.
 * @param sortBy The property IRI string to sort the Set of Things by.
 * @param offset The number of Things to skip.
 * @param limit The size of the page of Things to the return.
 * @param asc Whether the sorting should be ascending or descending.
 * @param filterFunction A Function to filter the set of Things.
 * @param <T> A class that extends Things.
 * @return A Response with a page of Things that has been filtered, sorted, and limited and headers for the total
 *      size and links to the next and prev pages if present.
 *///from w ww .  j  ava 2s  . c o m
private <T extends Thing> Response createPaginatedThingResponse(UriInfo uriInfo, Set<Resource> iris,
        Function<Resource, T> thingFunction, String sortBy, int offset, int limit, boolean asc,
        Function<T, Boolean> filterFunction) {
    if (offset > iris.size()) {
        throw ErrorUtils.sendError("Offset exceeds total size", Response.Status.BAD_REQUEST);
    }
    IRI sortIRI = factory.createIRI(sortBy);
    Comparator<T> comparator = Comparator.comparing(dist -> dist.getProperty(sortIRI).get().stringValue());
    Stream<T> stream = iris.stream().map(thingFunction);
    if (!asc) {
        comparator = comparator.reversed();
    }
    if (filterFunction != null) {
        stream = stream.filter(filterFunction::apply);
    }
    List<T> filteredThings = stream.collect(Collectors.toList());
    List<T> things = filteredThings.stream().sorted(comparator).skip(offset).limit(limit)
            .collect(Collectors.toList());
    return createPaginatedResponse(uriInfo, things, filteredThings.size(), limit, offset);
}

From source file:org.egov.tl.service.TradeLicenseService.java

private Map<String, Object> getReportParamsForCertificate(TradeLicense license, boolean isProvisional) {

    final Map<String, Object> reportParams = new HashMap<>();
    reportParams.put("applicationnumber", license.getApplicationNumber());
    reportParams.put("applicantName", license.getLicensee().getApplicantName());
    reportParams.put("licencenumber", license.getLicenseNumber());
    reportParams.put("wardName", license.getBoundary().getName());
    reportParams.put("cscNumber", "");
    reportParams.put("nameOfEstablishment", escapeXml(license.getNameOfEstablishment()));
    reportParams.put("licenceAddress", escapeXml(license.getAddress()));
    reportParams.put("municipality", cityService.getMunicipalityName());
    reportParams.put("district", cityService.getDistrictName());
    reportParams.put("category", escapeXml(license.getCategory().getName()));
    reportParams.put("subCategory", escapeXml(license.getTradeName().getName()));
    reportParams.put("appType", license.isNewApplication() ? "New Trade" : "Renewal");
    reportParams.put("currentDate", currentDateToDefaultDateFormat());
    reportParams.put("carporationulbType", getMunicipalityName().contains("Corporation"));
    Optional<EgDemandDetails> demandDetails = license.getCurrentDemand().getEgDemandDetails().stream()
            .sorted(Comparator.comparing(EgDemandDetails::getInstallmentEndDate).reversed())
            .filter(demandDetail -> demandDetail.getEgDemandReason().getEgDemandReasonMaster().getReasonMaster()
                    .equals(LICENSE_FEE_TYPE))
            .filter(demandDetail -> demandDetail.getAmtCollected().doubleValue() > 0).findFirst();
    BigDecimal amtPaid;//w w w .  j a  v  a  2s.c  om
    String installmentYear;
    if (demandDetails.isPresent()) {
        amtPaid = demandDetails.get().getAmtCollected();
        installmentYear = toYearFormat(demandDetails.get().getInstallmentStartDate()) + "-"
                + toYearFormat(demandDetails.get().getInstallmentEndDate());
    } else {
        throw new ValidationException("License Fee is not paid", "License Fee is not paid");
    }

    reportParams.put("installMentYear", installmentYear);
    reportParams.put("applicationdate", getDefaultFormattedDate(license.getApplicationDate()));
    reportParams.put("demandUpdateDate", getDefaultFormattedDate(license.getCurrentDemand().getModifiedDate()));
    reportParams.put("demandTotalamt", amtPaid);

    User approver;
    if (isProvisional || license.getApprovedBy() == null) {
        approver = licenseUtils.getCommissionerAssignment().getEmployee();
    } else {
        approver = license.getApprovedBy();
    }
    ByteArrayInputStream commissionerSign = new ByteArrayInputStream(
            approver == null || approver.getSignature() == null ? new byte[0] : approver.getSignature());
    reportParams.put("commissionerSign", commissionerSign);

    if (isProvisional)
        reportParams.put("certificateType", "provisional");
    else {
        reportParams.put("qrCode", license.qrCode(installmentYear, amtPaid));
    }

    return reportParams;
}

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

/**
 * Finds the rule in the device that mathces the input packet and has the highest priority.
 *
 * @param packet  the input packet// w ww . j  a va2 s  . c o m
 * @param in      the connect point the packet comes in from
 * @param tableId the table to search
 * @return the flow entry
 */
private FlowEntry matchHighestPriority(TrafficSelector packet, ConnectPoint in, TableId tableId) {
    //Computing the possible match rules.
    final Comparator<FlowEntry> comparator = Comparator.comparing(FlowRule::priority);
    return Lists.newArrayList(
            flowRuleService.getFlowEntriesByState(in.deviceId(), FlowEntry.FlowEntryState.ADDED).iterator())
            .stream().filter(flowEntry -> {
                return flowEntry.table().equals(tableId);
            }).filter(flowEntry -> {
                return match(packet, flowEntry);
            }).max(comparator).orElse(null);
}

From source file:org.egov.stms.transactions.service.SewerageApplicationDetailsService.java

public List<HashMap<String, Object>> populateHistory(
        final SewerageApplicationDetails sewerageApplicationDetails) {
    final List<HashMap<String, Object>> historyTable = new ArrayList<>();
    final State<Position> state = sewerageApplicationDetails.getState();
    if (state != null) {
        final HashMap<String, Object> stateMap = new HashMap<>();
        stateMap.put("date", state.getLastModifiedDate());
        stateMap.put("date", state.getDateInfo());
        stateMap.put("comments", state.getComments());
        stateMap.put("updatedBy", state.getSenderName());
        stateMap.put("status", state.getValue());
        setUserAndDepartment(state.getOwnerPosition(), stateMap);
        historyTable.add(stateMap);/*from   ww  w  .j  ava2s.  co  m*/
        state.getHistory().stream()
                .sorted(Comparator.comparing(StateHistory<Position>::getLastModifiedDate).reversed())
                .forEach(sh -> historyTable.add(updateHistoryTableInfo(sh)));
    }
    return historyTable;
}

From source file:org.egov.tl.service.TradeLicenseService.java

public List<HashMap<String, Object>> populateHistory(final TradeLicense tradeLicense) {
    final List<HashMap<String, Object>> processHistoryDetails = new ArrayList<>();
    if (tradeLicense.hasState()) {
        State<Position> state = tradeLicense.getCurrentState();
        final HashMap<String, Object> currentStateDetail = new HashMap<>();
        currentStateDetail.put("date", state.getLastModifiedDate());
        currentStateDetail.put("updatedBy",
                state.getSenderName().contains(DELIMITER_COLON)
                        ? state.getSenderName().split(DELIMITER_COLON)[1]
                        : state.getSenderName());
        currentStateDetail.put("status", state.isEnded() ? "Completed" : state.getValue());
        currentStateDetail.put("comments", defaultString(state.getComments()));
        User ownerUser = state.getOwnerUser();
        Position ownerPosition = state.getOwnerPosition();
        if (ownerPosition != null) {
            User usr = eisCommonService.getUserForPosition(ownerPosition.getId(), state.getLastModifiedDate());
            currentStateDetail.put("user", usr == null ? NA : usr.getName());
        } else//from w w  w  . j a va  2  s  . c o  m
            currentStateDetail.put("user", ownerUser == null ? NA : ownerUser.getName());

        processHistoryDetails.add(currentStateDetail);
        state.getHistory().stream()
                .sorted(Comparator.comparing(StateHistory<Position>::getLastModifiedDate).reversed())
                .forEach(sh -> processHistoryDetails.add(constructHistory(sh)));
    }
    return processHistoryDetails;
}

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

/**
 * Sets the awardCloseoutItems attribute value.
 * @param awardCloseoutItems The awardCloseoutItems to set.
 *//*www  .  j av  a 2  s .  c o  m*/
public void setAwardCloseoutItems(List<AwardCloseout> awardCloseoutItems) {
    if (awardCloseoutItems != null && awardCloseoutItems.size() > TOTAL_STATIC_REPORTS) {
        awardCloseoutNewItems.clear();
        for (int i = TOTAL_STATIC_REPORTS; i < awardCloseoutItems.size(); i++) {
            awardCloseoutNewItems.add(awardCloseoutItems.get(i));
        }
        for (int i = awardCloseoutItems.size(); i > TOTAL_STATIC_REPORTS; i--) {
            awardCloseoutItems.remove(i - 1);
        }
        Collections.sort(awardCloseoutNewItems, Comparator.comparing(AwardCloseout::getCloseoutReportName));
        awardCloseoutItems.addAll(TOTAL_STATIC_REPORTS, awardCloseoutNewItems);
    }
    this.awardCloseoutItems = awardCloseoutItems;
}

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

public AwardFandaRate getCurrentFandaRate() {
    List<AwardFandaRate> rates = this.getAwardFandaRate();
    Calendar calendar = Calendar.getInstance();
    int currentYear = calendar.get(Calendar.YEAR);

    // when both On and Off campus rates are in, send the higher one.
    // Ideally only one should be there
    // the single rate validation parameter needs to be set on award
    AwardFandaRate currentFandaRate = rates.stream()
            .filter(rate -> Integer.parseInt(rate.getFiscalYear()) == currentYear)
            .max(Comparator.comparing(AwardFandaRate::getApplicableFandaRate)).orElseGet(null);

    return currentFandaRate;
}

From source file:org.silverpeas.web.jobdomain.control.JobDomainPeasSessionController.java

public List<UserDetail> getRemovedUsers() throws AdminException {
    final List<UserDetail> removedUsers = adminCtrl.getRemovedUsersInDomain(this.targetDomainId);
    removedUsers.sort(Comparator.comparing(UserDetail::getStateSaveDate).thenComparing(UserDetail::getLastName)
            .thenComparing(UserDetail::getFirstName).thenComparing(UserDetail::getId));
    return removedUsers;
}

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

public List<AwardFundingProposal> getAllFundingProposalsSortedBySequence() {
    return getAllFundingProposals().stream()
            .sorted(Comparator.comparing(AwardFundingProposal::getAwardSequenceNumber))
            .collect(Collectors.toList());
}