Example usage for java.util Collections reverseOrder

List of usage examples for java.util Collections reverseOrder

Introduction

In this page you can find the example usage for java.util Collections reverseOrder.

Prototype

@SuppressWarnings("unchecked")
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp) 

Source Link

Document

Returns a comparator that imposes the reverse ordering of the specified comparator.

Usage

From source file:com.formtek.dashlets.sitetaskmgr.SiteTaskInstancesGet.java

private void sortTasks(List<WorkflowTask> allTasks, String sortColumn, String sortDirection) {
    logger.debug("Calling the sort method.");
    if (sortColumn == null || sortDirection == null) {
        logger.debug("Standard Sort order invoked");
        logger.debug("Number of tasks: " + allTasks.size());
        Collections.sort(allTasks, taskDueTaskComparator);
    } else {// ww  w  .  j a  v a2 s . c om
        if (sortColumn.equals("state")) {
            logger.debug("Sort by state");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskStateComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskStateComparator));
            }
        } else if (sortColumn.equals("priority")) {
            logger.debug("Sort by priority");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskWFPriorityComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskWFPriorityComparator));
            }
        } else if (sortColumn.equals("burden")) {
            logger.debug("Sort by burden");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskWFBurdenComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskWFBurdenComparator));
            }
        } else if (sortColumn.equals("name")) {
            logger.debug("Sort by state");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskWFNameComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskWFNameComparator));
            }
        } else if (sortColumn.equals("assignee")) {
            logger.debug("Sort by state");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskAssigneeComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskAssigneeComparator));
            }
        } else if (sortColumn.equals("initiator")) {
            logger.debug("Sort by state");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskWFInitiatorComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskWFInitiatorComparator));
            }
        } else if (sortColumn.equals("created")) {
            logger.debug("Sort by creation date");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskStartTaskComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskStartTaskComparator));
            }
        } else if (sortColumn.equals("due")) {
            logger.debug("Sort by due date");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskDueTaskComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskDueTaskComparator));
            }
        } else if (sortColumn.equals("percent")) {
            logger.debug("Sort by percent complete");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskWFPercentCompleteComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskWFPercentCompleteComparator));
            }
        } else if (sortColumn.equals("comment")) {
            logger.debug("Sort by comment");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskCommentComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskCommentComparator));
            }
        } else if (sortColumn.equals("prevcomment")) {
            logger.debug("Sort by previous comment");
            if (sortDirection.equals("asc")) {
                Collections.sort(allTasks, taskPrevCommentComparator);
            } else {
                Collections.sort(allTasks, Collections.reverseOrder(taskPrevCommentComparator));
            }
        } else {
            // Default sort order
            Collections.sort(allTasks, taskDueTaskComparator);
        }
    }
}

From source file:org.nuclos.client.ui.collect.model.SortableCollectableTableModelImpl.java

@Override
public void sort() {
    if (!sortKeys.isEmpty()) {
        List<Comparator<Clct>> comparators = new ArrayList<Comparator<Clct>>(sortKeys.size());
        for (SortKey sortKey : sortKeys) {
            Comparator<Clct> columnComparator = getComparator(sortKey.getColumn());
            if (columnComparator == null)
                continue;
            switch (sortKey.getSortOrder()) {
            case DESCENDING:
                columnComparator = Collections.reverseOrder(columnComparator);
                // fall-through
            case ASCENDING:
                comparators.add(columnComparator);
                break;
            }/*from  w  w w. j  a  va2s .  c  o m*/
        }
        // always add id comparator as compound.
        comparators.add(
                (Comparator<Clct>) CollectableComparatorFactory.getInstance().newCollectableIdComparator());

        //if (!comparators.isEmpty()) { // will never happen.
        // This can happen if some sort keys with UNSORTED ordering are provided
        Comparator<Clct> comparator = ComparatorUtils.compoundComparator(comparators);
        this.sort(comparator);
        this.fireTableDataSorted();
        //}
    }
}

From source file:org.sakaiproject.site.tool.EnrolmentsHandler.java

/**
 * Get a sublist of the current user's enrolments that is paged and sorted.
 * /*from  ww  w  .ja  v a  2  s  .c o m*/
 * @param page the page requested
 * @param sortMode the sort mode requested
 * @param sortAsc true if sorting ascending; false otherwise
 * @param isFiltered true if the list is filtered based on user's provided search term; false otherwise
 * @return the requested sublist
 */
public List<Enrolment> getSortedAndPagedEnrolments(PagingPosition page, String sortMode, boolean sortAsc,
        boolean isFiltered) {
    // Get the current user ID; double check the cache; use the appropriate list (filtered or not)
    String currentUserID = UDS.getCurrentUser().getId();
    if (enrolmentsCacheMap.get(currentUserID) == null) {
        getSectionEnrolments(currentUserID);
    }
    List<Enrolment> retVal = isFiltered ? filteredEnrolments
            : enrolmentsCacheMap.get(currentUserID).getEnrolments();

    // Apply the requested sort
    if (USE_TERM_SORT.equals(sortMode)) {
        retVal = sortByTerm(retVal, sortAsc);
    } else if (USE_SECTION_SORT.equals(sortMode)) {
        Collections.sort(retVal, sortAsc ? SECTION_COMP : Collections.reverseOrder(SECTION_COMP));
    } else if (USE_SITE_SORT.equals(sortMode)) {
        retVal = sortBySiteTitle(retVal, sortAsc);
    }

    // Return the requested page (sub list)
    return retVal.subList(page.getFirst() > page.getLast() ? 0 : page.getFirst() - 1,
            page.getLast() > retVal.size() ? retVal.size() : page.getLast());
}

From source file:org.languagetool.rules.spelling.suggestions.XGBoostSuggestionsOrderer.java

@Override
public List<SuggestedReplacement> orderSuggestions(List<String> suggestions, String word,
        AnalyzedSentence sentence, int startPos) {
    if (!isMlAvailable()) {
        throw new IllegalStateException("Illegal call to orderSuggestions() - isMlAvailable() returned false.");
    }//from w w  w.j a  v  a2 s.  co  m
    long featureStartTime = System.currentTimeMillis();

    String langCode = language.getShortCodeWithCountryAndVariant();

    Pair<List<SuggestedReplacement>, SortedMap<String, Float>> candidatesAndFeatures = computeFeatures(
            suggestions, word, sentence, startPos);
    //System.out.printf("Computing %d features took %d ms.%n", suggestions.size(), System.currentTimeMillis() - featureStartTime);
    List<SuggestedReplacement> candidates = candidatesAndFeatures.getLeft();
    SortedMap<String, Float> matchFeatures = candidatesAndFeatures.getRight();
    List<SortedMap<String, Float>> suggestionFeatures = candidates.stream()
            .map(SuggestedReplacement::getFeatures).collect(Collectors.toList());
    if (candidates.isEmpty()) {
        return Collections.emptyList();
    }
    if (candidates.size() != suggestionFeatures.size()) {
        throw new RuntimeException(
                String.format("Mismatch between candidates and corresponding feature list: length %d / %d",
                        candidates.size(), suggestionFeatures.size()));
    }

    int numFeatures = matchFeatures.size() + topN * suggestionFeatures.get(0).size(); // padding with zeros
    float[] data = new float[numFeatures];

    int featureIndex = 0;
    //System.out.printf("Features for match on '%s': %n", word);
    int expectedMatchFeatures = matchFeatureCount.getOrDefault(langCode, -1);
    int expectedCandidateFeatures = candidateFeatureCount.getOrDefault(langCode, -1);
    if (matchFeatures.size() != expectedMatchFeatures) {
        logger.warn(String.format("Match features '%s' do not have expected size %d.", matchFeatures,
                expectedMatchFeatures));
    }
    for (Map.Entry<String, Float> feature : matchFeatures.entrySet()) {
        //System.out.printf("%s = %f%n", feature.getKey(), feature.getValue());
        data[featureIndex++] = feature.getValue();
    }
    //int suggestionIndex = 0;
    for (SortedMap<String, Float> candidateFeatures : suggestionFeatures) {
        if (candidateFeatures.size() != expectedCandidateFeatures) {
            logger.warn(String.format("Candidate features '%s' do not have expected size %d.",
                    candidateFeatures, expectedCandidateFeatures));
        }
        //System.out.printf("Features for candidate '%s': %n", candidates.get(suggestionIndex++).getReplacement());
        for (Map.Entry<String, Float> feature : candidateFeatures.entrySet()) {
            //System.out.printf("%s = %f%n", feature.getKey(), feature.getValue());
            data[featureIndex++] = feature.getValue();
        }
    }
    List<Integer> labels = modelClasses.get(langCode);

    Booster model = null;
    try {
        long modelStartTime = System.currentTimeMillis();
        model = modelPool.borrowObject(language);
        //System.out.printf("Loading model took %d ms.%n", System.currentTimeMillis() - modelStartTime);
        DMatrix matrix = new DMatrix(data, 1, numFeatures);
        long predictStartTime = System.currentTimeMillis();
        float[][] output = model.predict(matrix);
        //System.out.printf("Prediction took %d ms.%n", System.currentTimeMillis() - predictStartTime);
        if (output.length != 1) {
            throw new XGBoostError(String.format(
                    "XGBoost returned array with first dimension of length %d, expected 1.", output.length));
        }
        float[] probabilities = output[0];
        if (probabilities.length != labels.size()) {
            throw new XGBoostError(
                    String.format("XGBoost returned array with second dimension of length %d, expected %d.",
                            probabilities.length, labels.size()));
        }
        // TODO: could react to label -1 (not in list) by e.g. evaluating more candidates
        //if (labels.get(0) != -1) {
        //  throw new IllegalStateException(String.format(
        //    "Expected first label of ML ranking model to be -1 (= suggestion not in list), was %d", labels.get(0)));
        //}
        //float notInListProbabilily = probabilites[0];
        for (int candidateIndex = 0; candidateIndex < candidates.size(); candidateIndex++) {
            int labelIndex = labels.indexOf(candidateIndex);
            float prob = 0.0f;
            if (labelIndex != -1) {
                prob = probabilities[labelIndex];
            }
            candidates.get(candidateIndex).setConfidence(prob);
        }
    } catch (XGBoostError xgBoostError) {
        logger.error("Error while applying XGBoost model to spelling suggestions", xgBoostError);
        return candidates;
    } catch (Exception e) {
        logger.error("Error while loading XGBoost model for spelling suggestions", e);
        return candidates;
    } finally {
        if (model != null) {
            try {
                modelPool.returnObject(language, model);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    candidates.sort(Collections.reverseOrder(Comparator.comparing(SuggestedReplacement::getConfidence)));
    return candidates;
}

From source file:org.openmrs.module.casereport.CaseReportForm.java

private DatedUuidAndValue getMostRecentValue(List<DatedUuidAndValue> values) {
    Collections.sort(values, Collections.reverseOrder(comparator));
    return values.isEmpty() ? null : values.get(0);
}

From source file:org.kuali.rice.kns.web.struts.form.KualiTableRenderFormMetadata.java

/**
 * Sorts a list on the form according to the form metadata (sortColumName, previouslySortedColumnName)
 *
 * @param memberTableMetadata/*from   w w  w.  j a  v  a 2  s. co  m*/
 * @param items
 * @param maxRowsPerPage
 * @throws org.kuali.rice.kew.api.exception.WorkflowException
 */
public void sort(List<?> items, int maxRowsPerPage) {

    // Don't bother to sort null, empty or singleton lists
    if (items == null || items.size() <= 1)
        return;

    String columnToSortOn = getColumnToSortName();

    // Don't bother to sort if no column to sort on is provided
    if (StringUtils.isEmpty(columnToSortOn))
        return;

    String previouslySortedColumnName = getPreviouslySortedColumnName();

    // We know members isn't null or empty from the check above
    Object firstItem = items.get(0);
    // Need to decide if the comparator is for a bean property or a mapped key on the qualififer attribute set
    Comparator comparator = null;
    Comparator subComparator = new Comparator<Object>() {

        public int compare(Object o1, Object o2) {
            if (o1 == null)
                return -1;
            if (o2 == null)
                return 1;

            if (o1 instanceof java.util.Date && o2 instanceof java.util.Date) {
                Date d1 = (Date) o1;
                Date d2 = (Date) o2;
                return d1.compareTo(d2);
            }

            String s1 = o1.toString();
            String s2 = o2.toString();
            int n1 = s1.length(), n2 = s2.length();
            for (int i1 = 0, i2 = 0; i1 < n1 && i2 < n2; i1++, i2++) {
                char c1 = s1.charAt(i1);
                char c2 = s2.charAt(i2);
                if (c1 != c2) {
                    c1 = Character.toUpperCase(c1);
                    c2 = Character.toUpperCase(c2);
                    if (c1 != c2) {
                        c1 = Character.toLowerCase(c1);
                        c2 = Character.toLowerCase(c2);
                        if (c1 != c2) {
                            return c1 - c2;
                        }
                    }
                }
            }
            return n1 - n2;
        }
    };
    // If the columnName is a readable bean property on the first member, then it's safe to say we need a simple bean property comparator,
    // otherwise it's a mapped property -- syntax for BeanComparator is "name" and "name(key)", respectively
    if (PropertyUtils.isReadable(firstItem, columnToSortOn))
        comparator = new BeanComparator(columnToSortOn, subComparator);
    else
        comparator = new BeanComparator(
                new StringBuilder().append("qualifierAsMap(").append(columnToSortOn).append(")").toString(),
                subComparator);

    // If the user has decided to resort by the same column that the list is currently sorted by, then assume that s/he wants to reverse the order of the sort
    if (!StringUtils.isEmpty(columnToSortOn) && !StringUtils.isEmpty(previouslySortedColumnName)
            && columnToSortOn.equals(previouslySortedColumnName)) {
        // we're already sorted on the same column that the user clicked on, so we reverse the list
        if (isSortDescending())
            comparator = Collections.reverseOrder(comparator);

        setSortDescending(!isSortDescending());
    } else {
        // Track which column we're currently sorting, so that the above logic will work on the next sort
        setPreviouslySortedColumnName(columnToSortOn);
        setSortDescending(true);
    }

    //if the user is just going between pages no need to sort
    if (getSwitchToPageNumber() == getViewedPageNumber()) {
        Collections.sort(items, comparator);
    }

    jumpToFirstPage(items.size(), maxRowsPerPage);
}

From source file:org.polymap.rhei.table.FormFeatureTableColumn.java

public Comparator<IFeatureTableElement> newComparator(int sortDir) {
    Comparator<IFeatureTableElement> result = null;
    if (sorter != null) {
        result = sorter;//w w  w.  java 2  s  . c o  m
    } else {
        result = new Comparator<IFeatureTableElement>() {

            private String sortPropName = getName();
            private ColumnLabelProvider lp = getLabelProvider();

            @Override
            public int compare(IFeatureTableElement elm1, IFeatureTableElement elm2) {
                // the value from the elm or String from LabelProvider as fallback
                Object value1 = elm1.getValue(sortPropName);
                Object value2 = elm2.getValue(sortPropName);

                if (value1 == null && value2 == null) {
                    return 0;
                } else if (value1 == null) {
                    return -1;
                } else if (value2 == null) {
                    return 1;
                } else if (!value1.getClass().equals(value2.getClass())) {
                    throw new RuntimeException("Column types do not match: " + value1.getClass().getSimpleName()
                            + " - " + value2.getClass().getSimpleName());
                } else if (value1 instanceof String) {
                    return ((String) value1).compareToIgnoreCase((String) value2);
                } else if (value1 instanceof Number) {
                    return (int) (((Number) value1).doubleValue() - ((Number) value2).doubleValue());
                } else if (value1 instanceof Date) {
                    return ((Date) value1).compareTo((Date) value2);
                } else {
                    throw new RuntimeException("Unable to compare value: " + value1);
                    //return value1.toString().compareTo( value2.toString() );
                }
            }
        };
    }
    return sortDir == SWT.UP ? Collections.reverseOrder(result) : result;
}

From source file:org.sakaiproject.site.tool.EnrolmentsHandler.java

/**
 * Sort the given list of Enrolments by the first site title tied to it (if any)
 * /*from   ww w  .jav a 2 s.  com*/
 * @param list the list to be sorted
 * @param sortAsc true if sorting ascending; false otherwise
 * @return the sorted list
 */
private List<Enrolment> sortBySiteTitle(List<Enrolment> list, boolean sortAsc) {
    Comparator<Enrolment> comp = (Enrolment obj1, Enrolment obj2) -> {
        String siteTitle1 = "";
        for (SiteTitleUrlWrapper site : obj1.getSiteWrappers()) {
            siteTitle1 = site.getSiteTitle();
            break;
        }

        String siteTitle2 = "";
        for (SiteTitleUrlWrapper site : obj2.getSiteWrappers()) {
            siteTitle2 = site.getSiteTitle();
            break;
        }

        return siteTitle1.compareTo(siteTitle2);
    };

    Collections.sort(list, sortAsc ? comp : Collections.reverseOrder(comp));
    return list;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.phd.CommonPhdIndividualProgramProcessDA.java

public ActionForward viewProcessAlertMessages(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {

    TreeSet<PhdAlertMessage> orderedMessages = new TreeSet<PhdAlertMessage>(
            Collections.reverseOrder(PhdAlertMessage.COMPARATOR_BY_WHEN_CREATED_AND_ID));
    orderedMessages.addAll(getProcess(request).getAlertMessagesForLoggedPerson());
    ArrayList<PhdAlertMessage> lastMessages = new ArrayList<PhdAlertMessage>();
    lastMessages.addAll(orderedMessages);

    request.setAttribute("unread", "false");
    request.setAttribute("alertMessages",
            lastMessages.subList(0, Math.min(lastMessages.size(), NUMBER_OF_LAST_MESSAGES)));
    request.setAttribute("tooManyMessages", (lastMessages.size() > NUMBER_OF_LAST_MESSAGES) ? "true" : "false");
    return mapping.findForward("viewProcessAlertMessages");
}

From source file:org.wso2.carbon.andes.admin.mqtt.AndesMQTTAdminService.java

/**
 * Retrieve subscriptions matching to the given search criteria.
 *
 * @param isDurable  are the subscriptions to be retrieve durable (true/ false)
 * @param isActive   are the subscriptions to be retrieved active (true/false)
 * @param protocolType  the protocol type of the subscriptions to be retrieved
 * @param destinationType the destination type of the subscriptions to be retrieved
 * @param filteredNamePattern queue or topic name pattern to search the subscriptions ("" for all)
 * @param isFilteredNameByExactMatch exactly match the name or not
 * @param identifierPattern  identifier pattern to search the subscriptions ("" for all)
 * @param isIdentifierPatternByExactMatch  exactly match the identifier or not
 * @param ownNodeId node Id of the node which own the subscriptions
 * @param pageNumber  page number in the pagination table
 * @param subscriptionCountPerPage  number of subscriptions to be shown in the UI per page
 * @return a list of subscriptions which match to the search criteria
 * @throws BrokerManagerAdminException throws when an error occurs
 *///www . ja v a  2  s  . co  m
public Subscription[] getFilteredSubscriptions(boolean isDurable, boolean isActive, String protocolType,
        String destinationType, String filteredNamePattern, boolean isFilteredNameByExactMatch,
        String identifierPattern, boolean isIdentifierPatternByExactMatch, String ownNodeId, int pageNumber,
        int subscriptionCountPerPage) throws BrokerManagerAdminException {
    List<Subscription> allSubscriptions = new ArrayList<>();
    Subscription[] subscriptionsDTO;

    try {
        SubscriptionManagerService subscriptionManagerService = AndesBrokerManagerMQTTAdminServiceDSHolder
                .getInstance().getSubscriptionManagerService();
        List<org.wso2.carbon.andes.core.types.Subscription> subscriptions = subscriptionManagerService
                .getFilteredSubscriptions(isDurable, isActive, protocolType, destinationType,
                        filteredNamePattern, isFilteredNameByExactMatch, identifierPattern,
                        isIdentifierPatternByExactMatch, ownNodeId, pageNumber, subscriptionCountPerPage);
        subscriptionsDTO = new Subscription[subscriptions.size()];
        for (org.wso2.carbon.andes.core.types.Subscription sub : subscriptions) {
            Subscription subscriptionDTO = new Subscription();
            subscriptionDTO.setSubscriptionIdentifier(sub.getSubscriptionIdentifier());
            subscriptionDTO.setSubscribedQueueOrTopicName(sub.getSubscribedQueueOrTopicName());
            subscriptionDTO.setSubscriberQueueBoundExchange(sub.getSubscriberQueueBoundExchange());
            subscriptionDTO.setSubscriberQueueName(sub.getSubscriberQueueName());
            subscriptionDTO.setDurable(sub.isDurable());
            subscriptionDTO.setActive(sub.isActive());
            subscriptionDTO
                    .setNumberOfMessagesRemainingForSubscriber(sub.getNumberOfMessagesRemainingForSubscriber());
            subscriptionDTO.setConnectedNodeAddress(sub.getConnectedNodeAddress());
            subscriptionDTO.setProtocolType(sub.getProtocolType());
            subscriptionDTO.setDestinationType(sub.getDestinationType());
            subscriptionDTO.setOriginHostAddress(sub.getOriginHostAddress());

            allSubscriptions.add(subscriptionDTO);
        }
        CustomSubscriptionComparator comparator = new CustomSubscriptionComparator();
        Collections.sort(allSubscriptions, Collections.reverseOrder(comparator));
        allSubscriptions.toArray(subscriptionsDTO);
    } catch (SubscriptionManagerException e) {
        String errorMessage = "An error occurred while retrieving subscriptions from backend " + e.getMessage();
        log.error(errorMessage, e);
        throw new BrokerManagerAdminException(errorMessage, e);
    }
    return subscriptionsDTO;
}