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() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Usage

From source file:org.onehippo.forge.blog.components.socialmedia.TwitterListing.java

/**
 * Fetches both Tweets and ReTweets for the configured user.
 * Adds them combined in a reversed order (newest first) to the {@link HstRequest}.
 * <p/>/*www. ja  va2 s .c  o m*/
 * Required parameters:
 * <dl>
 * <dt>token</dt>
 * <dd>needed for oAuth {@link twitter4j.http.AccessToken}</dd>
 * <dt>tokenSecret</dt>
 * <dd>needed for oAuth {@link twitter4j.http.AccessToken}</dd>
 * <dt>consumerKey<dt>
 * <dd>needed for oAuth</dd>
 * <dt>consumerSecret<dt>
 * <dd>needed for oAuth</dd>
 * </dl>
 */
@Override
public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
    super.doBeforeRender(request, response);

    request.setAttribute("boxTitle", getParameter("boxTitle", request));

    Twitter twitter = getTwitterObject(request);
    if (twitter == null) {
        return;
    }

    try {
        List<Status> statuses = twitter.getUserTimeline();
        // for backwards compatibility Twitter does not return retweets when the user timeline is requested
        // that's why we have to merge them
        List<Status> retweets = twitter.getRetweetedByMe();
        statuses.addAll(retweets);
        Set<Status> allStatuses = new TreeSet<Status>(Collections.reverseOrder());
        allStatuses.addAll(statuses);
        allStatuses.addAll(retweets);
        if (!allStatuses.isEmpty()) {
            request.setAttribute("statuses", allStatuses);
        }
    } catch (TwitterException e) {
        log.warn("Error getting Twitter status updates", e);
    }

}

From source file:org.kuali.kpme.tklm.common.CalendarApprovalFormAction.java

protected void setCalendarFields(CalendarApprovalForm calendarApprovalForm) {
    Set<String> calendarYears = new TreeSet<String>(Collections.reverseOrder());
    List<CalendarEntry> calendarEntries = getCalendarEntries(calendarApprovalForm.getCalendarEntry());

    for (CalendarEntry calendarEntry : calendarEntries) {
        String calendarEntryYear = calendarEntry.getBeginPeriodFullDateTime().toString("yyyy");
        calendarYears.add(calendarEntryYear);
    }//from w w  w .j  a v  a  2s .c o m

    String currentCalendarYear = calendarApprovalForm.getCalendarEntry().getBeginPeriodFullDateTime()
            .toString("yyyy");
    String selectedCalendarYear = StringUtils.isNotBlank(calendarApprovalForm.getSelectedCalendarYear())
            ? calendarApprovalForm.getSelectedCalendarYear()
            : currentCalendarYear;

    calendarApprovalForm.setCalendarYears(new ArrayList<String>(calendarYears));
    calendarApprovalForm.setPayPeriodsMap(ActionFormUtils.getPayPeriodsMap(
            ActionFormUtils.getAllCalendarEntriesForYear(calendarEntries, selectedCalendarYear), null));

    calendarApprovalForm.setSelectedCalendarYear(selectedCalendarYear);
    calendarApprovalForm.setSelectedPayPeriod(calendarApprovalForm.getCalendarEntry().getHrCalendarEntryId());
}

From source file:io.cloudex.framework.partition.builtin.BinPackingPartition.java

@Override
public List<Partition> partition() {

    Validate.notNull(this.items);

    // sort descending
    Collections.sort(items, Collections.reverseOrder());

    // have we got a maximum set?, otherwise use the size of the largest item
    Long max = (this.maxBinItems != null) ? this.maxBinItems : items.get(0).getWeight();

    PartitionUtils.setScale(items, max);

    long sum = PartitionUtils.sum(items, max);

    // check if the number of bins have already been set, in which case we have to fit everything in them
    if (this.numberOfBins == null) {
        // lower bound number of bin
        double numBins = (sum / (float) max);
        double numWholeBins = Math.floor(numBins);
        this.numberOfBins = (int) numWholeBins;
        double excess = numBins - numWholeBins;
        if (excess > newBinPercentage) {
            this.numberOfBins++;
        }//from   w ww. java 2 s  . c om

    } else {
        max = (long) Math.ceil(sum / (float) this.numberOfBins);
    }

    List<Partition> bins = new ArrayList<>();

    if (this.numberOfBins == 1) {

        Partition bin = new Partition();
        bins.add(bin);
        bin.addAll(items);
        items.clear();

    } else {

        // Mix of First Fit Decreasing (FFD) strategy and Full Bin strategy
        for (int i = 0; i < this.numberOfBins; i++) {
            Partition bin = new Partition();
            bins.add(bin);

            // check if we have ran out of items
            if (!items.isEmpty()) {

                Item largestItem = items.get(0);

                bin.add(largestItem);
                items.remove(largestItem);

                Long currentSum = bin.sum();

                if (currentSum < max) {
                    Long diff = max - currentSum;
                    List<Item> toRemove = new ArrayList<>();

                    for (Item item : items) {
                        //Item item = items.get(j);
                        if (item.getWeight() <= diff) {

                            bin.add(item);
                            toRemove.add(item);

                            if (item.getWeight() == diff) {
                                break;
                            } else {
                                // look for an even small number to fill the gap
                                diff = max - bin.sum();
                            }
                        }
                    }

                    items.removeAll(toRemove);

                }
            }
            bin.calculateScale();
        }

        /*if(!items.isEmpty()) {
        bins.get(bins.size() - 1).addAll(items);
        items.clear();
        }*/

        // spread out remaining items, this approximate
        if (!items.isEmpty()) {
            //bins.get(bins.size() - 1).addAll(items);
            //items.clear();

            // items are in descending order
            // sort partitions in ascending order
            Collections.sort(bins);

            Partition smallest;
            long largestSum = bins.get(bins.size() - 1).sum();
            int index = 0;
            do {

                smallest = bins.get(index);

                // spread the remaining items into the bins, largest item into smallest bin
                for (int i = 0; i < items.size(); i++) {

                    smallest.add(items.remove(i));

                    if (smallest.sum() > largestSum) {
                        break;
                    }
                }

                index++;

            } while (!items.isEmpty());

            items.clear();
        }

    }

    return bins;

}

From source file:org.kuali.kra.common.committee.lookup.keyvalue.CommitteeIdValuesFinderBase.java

/**
 * This method will return the list of all highest-sequence number committee instances.
 * Will always return non-null (but possibly empty) collection.
 *///w  w w. ja va  2 s.  c o m
public List<CommitteeBase> getActiveCommittees() {
    ArrayList<CommitteeBase> returnCommitteeList = new ArrayList<CommitteeBase>();

    // TODO *********commented the code below during IACUC refactoring*********         
    //        Collection<CommonCommittee> committees = this.getBusinessObjectService().findAll(CommonCommittee.class);

    Collection<? extends CommitteeBase> committees = this.getBusinessObjectService()
            .findAll(getCommitteeBOClassHook());
    // sort and iterate through to get only the latest instances
    if (CollectionUtils.isNotEmpty(committees)) {
        List<String> committeeIds = new ArrayList<String>();
        // only the active ones
        Collections.sort((List<CommitteeBase>) committees, Collections.reverseOrder());
        for (CommitteeBase committee : committees) {
            if (!committeeIds.contains(committee.getCommitteeId())) {
                returnCommitteeList.add(committee);
                committeeIds.add(committee.getCommitteeId());
            }
        }
    }

    return returnCommitteeList;
}

From source file:io.cloudex.framework.partition.builtin.BinPackingPartition1.java

@Override
public List<Partition> partition() {

    Validate.notNull(this.items);

    // sort descending
    Collections.sort(items, Collections.reverseOrder());

    /*long seed = System.nanoTime();
    Collections.shuffle(items, new Random(seed));*/

    // have we got a maximum set?, otherwise use the size of the largest item
    Long max = (this.maxBinItems != null) ? this.maxBinItems : items.get(0).getWeight();

    PartitionUtils.setScale(items, max);

    long sum = PartitionUtils.sum(items, max);

    // check if the number of bins have already been set, in which case we have to fit everything in them
    if (this.numberOfBins == null) {
        // lower bound number of bin
        double numBins = (sum / (float) max);
        double numWholeBins = Math.floor(numBins);
        this.numberOfBins = (int) numWholeBins;
        double excess = numBins - numWholeBins;
        if (excess > newBinPercentage) {
            this.numberOfBins++;
        }//  www  .  j  a v a 2  s  . co  m

    } else {
        max = (long) Math.ceil(sum / (float) this.numberOfBins);
    }

    List<Partition> bins = new ArrayList<>();

    if (this.numberOfBins == 1) {

        Partition bin = new Partition();
        bins.add(bin);
        bin.addAll(items);
        items.clear();

    } else {

        // create all the bins
        for (int i = 0; i < this.numberOfBins; i++) {
            bins.add(new Partition(max));
        }

        List<Item> toRemove = new ArrayList<>();

        int binIndex = 0;

        for (Item item : items) {

            // iterate over bins and try to put the item into the first one it fits into

            Partition startBin = bins.get(binIndex);
            ;
            Partition currentBin = null;
            int count = 0;

            while (!toRemove.contains(item)) { // did we put the item in a bin?

                currentBin = bins.get(binIndex);

                if ((count != 0) && (currentBin == startBin)) {
                    // back where we started item did not fit in last bin. move on
                    break;

                }

                if (currentBin.addIfPossible(item)) {
                    // item fit in bin
                    toRemove.add(item);
                }

                // try next bin
                binIndex++;

                if (binIndex == bins.size()) {
                    // go back to the beginning
                    binIndex = 0;
                }

                count++;

            }
        }

        items.removeAll(toRemove);

        // spread out remaining items, this approximate
        if (!items.isEmpty()) {
            //bins.get(bins.size() - 1).addAll(items);
            //items.clear();

            // items are in descending order
            // sort partitions in ascending order
            Collections.sort(bins);
            //Collections.sort(items, Collections.reverseOrder());

            Partition smallest;
            long largestSum = bins.get(bins.size() - 1).sum();
            int index = 0;
            do {

                smallest = bins.get(index);

                // spread the remaining items into the bins, largest item into smallest bin
                for (int i = 0; i < items.size(); i++) {

                    smallest.add(items.remove(i));

                    if (smallest.sum() > largestSum) {
                        break;
                    }
                }

                index++;
                // there is a large item we can't break
                if (!items.isEmpty() && (index >= bins.size())) {
                    bins.get(index - 1).addAll(items);
                    items.clear();
                }

            } while (!items.isEmpty());

            items.clear();
        }

        for (Partition bin : bins) {
            bin.calculateScale();
        }

    }

    return bins;

}

From source file:com.graphaware.module.algo.generator.BarabasiAlbertGeneratorTest.java

@Test
public void shouldGeneratePowerLawDistribution() {
    GraphDatabaseService database = new TestGraphDatabaseFactory().newImpermanentDatabase();

    new Neo4jGraphGenerator(database).generateGraph(getGeneratorConfiguration(100, 2));

    List<Integer> degrees = new LinkedList<>();

    try (Transaction tx = database.beginTx()) {
        for (Node node : GlobalGraphOperations.at(database).getAllNodes()) {
            degrees.add(node.getDegree());
        }//from ww w  .j  ava  2 s  .c  o m
        tx.success();
    }

    Collections.sort(degrees, Collections.reverseOrder());

    //todo make this an automated test
    System.out.println(ArrayUtils.toString(degrees.toArray(new Integer[degrees.size()])));

    database.shutdown();
}

From source file:ddf.mime.mapper.MimeTypeToTransformerMapperImpl.java

@Override
public <T> List<T> findMatches(Class<T> clazz, MimeType userMimeType) {
    BundleContext bundleContext = getContext();
    ServiceReference[] refs = null;/* w  w  w. j  a v  a  2  s. com*/
    List<T> list = new ArrayList<T>();

    if (bundleContext == null) {
        LOGGER.debug("Cannot find matches, bundle context is null.");
        return list;
    }
    if (clazz == null) {
        LOGGER.warn("Cannot find matches, service argument is null.");
        throw new IllegalArgumentException("Invalid argument supplied, null service argument");
    }

    /*
     * Extract the services using the bundle context.
     */
    try {
        refs = bundleContext.getServiceReferences(clazz.getName(), null);
    } catch (InvalidSyntaxException e) {
        LOGGER.warn("Invalid filter syntax ", e);
        throw new IllegalArgumentException("Invalid syntax supplied: " + userMimeType.toString());
    }

    // If no InputTransformers found, return empty list
    if (refs == null) {
        LOGGER.debug("No {} services found - return empty list", clazz.getName());
        return list;
    }

    /*
     * Sort the list of service references based in it's Comparable interface.
     */
    Arrays.sort(refs, Collections.reverseOrder());

    /*
     * If the mime type is null return the whole list of service references
     */
    if (userMimeType == null) {
        if (refs.length > 0) {
            for (ServiceReference ref : refs) {
                Object service = (bundleContext.getService(ref));
                T typedService = clazz.cast(service);
                list.add(typedService);
            }
        }
        return list;
    }

    String userIdValue = userMimeType.getParameter(MimeTypeToTransformerMapper.ID_KEY);
    List<T> strictlyMatching = new ArrayList<T>();

    for (ServiceReference ref : refs) {

        List<String> mimeTypesServicePropertyList = getServiceMimeTypesList(ref);

        String serviceId = getServiceId(ref);

        for (String mimeTypeRawEntry : mimeTypesServicePropertyList) {

            MimeType mimeTypeEntry = constructMimeType(mimeTypeRawEntry);

            if (mimeTypeEntry != null
                    && StringUtils.equals(mimeTypeEntry.getBaseType(), userMimeType.getBaseType())
                    && (userIdValue == null || StringUtils.equals(userIdValue, serviceId))) {

                try {
                    Object service = bundleContext.getService(ref);
                    T typedService = clazz.cast(service);
                    strictlyMatching.add(typedService);
                    break; // found exact mimetype, no need to continue within
                    // the same service

                } catch (ClassCastException cce) {
                    LOGGER.debug("Caught illegal cast to transformer type. ", cce);
                }
            }
        }
    }

    return strictlyMatching;
}

From source file:io.seldon.recommendation.combiner.ScoreOrderCombiner.java

@Override
public RecommendationPeer.RecResultContext combine(int numRecsRequired,
        List<RecommendationPeer.RecResultContext> resultsSets) {
    Map<Long, String> item_recommender_lookup = new HashMap<>();
    List<String> validAlgs = new ArrayList<>();
    Map<ItemRecommendationResultSet.ItemRecommendationResult, Float> scores = new HashMap<>();
    List<ItemRecommendationResultSet.ItemRecommendationResult> ordered = new ArrayList<>();
    for (RecommendationPeer.RecResultContext set : resultsSets) {
        if (set.resultSet.getResults().size() > 0)
            validAlgs.add(set.algKey);//  w w  w .ja  v  a 2 s  .  com
        for (ItemRecommendationResultSet.ItemRecommendationResult itemRecommendationResult : set.resultSet
                .getResults()) {
            Float previousResult = scores.get(itemRecommendationResult);
            if (previousResult != null) {
                if (previousResult < itemRecommendationResult.score)
                    scores.put(itemRecommendationResult, itemRecommendationResult.score);
                capture_recommender_used_for_item(item_recommender_lookup, itemRecommendationResult, set);
            } else {
                scores.put(itemRecommendationResult, itemRecommendationResult.score);
                capture_recommender_used_for_item(item_recommender_lookup, itemRecommendationResult, set);
            }
        }
    }
    ordered.addAll(scores.keySet());
    Collections.sort(ordered, Collections.reverseOrder());
    RecommendationPeer.RecResultContext recResultContext = new RecommendationPeer.RecResultContext(
            new ItemRecommendationResultSet(ordered, StringUtils.join(validAlgs, ':')),
            StringUtils.join(validAlgs, ':'));
    recResultContext.item_recommender_lookup = item_recommender_lookup;
    return recResultContext;
}