Example usage for java.util Comparator Comparator

List of usage examples for java.util Comparator Comparator

Introduction

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

Prototype

Comparator

Source Link

Usage

From source file:com.c123.billbuddy.dal.Top5MerchantFeeAmountReducer.java

public Merchant[] reduce(SpaceRemotingResult<Merchant[]>[] results, SpaceRemotingInvocation remotingInvocation)
        throws Exception {

    log.info("Starting Top5MerchantFeeAmountReducer");

    List<Merchant> merchants = new ArrayList<Merchant>();

    // Each result is an array of events. Each result is from a single partition.        
    for (SpaceRemotingResult<Merchant[]> result : results) {
        if (result.getException() != null) {
            // just log the fact that there was an exception
            log.error("Executor Remoting Exception [" + result.getException() + "]");

            continue;
        }/*from  w w w. ja v a  2  s.  c  o  m*/
        Collections.addAll(merchants, result.getResult());
    }

    Collections.sort(merchants, new Comparator<Merchant>() {
        public int compare(Merchant p1, Merchant p2) {
            return p2.getFeeAmount().compareTo(p1.getFeeAmount());
        }
    });

    // If the number of results needed is less than the number of events that were reduced, then
    // return a sublist. Otherwise, return the entire list of events.
    Merchant[] top5Merchant;
    if (merchants.size() < 5) {
        top5Merchant = new Merchant[merchants.size()];
        merchants.toArray(top5Merchant);
    } else {
        top5Merchant = new Merchant[5];
        merchants.subList(0, 5).toArray(top5Merchant);
    }
    return top5Merchant;
}

From source file:springfox.documentation.spring.web.readers.operation.HandlerMethodResolver.java

@VisibleForTesting
static Ordering<ResolvedMethod> byArgumentCount() {
    return Ordering.from(new Comparator<ResolvedMethod>() {
        @Override/*ww w  .  ja v  a  2 s . com*/
        public int compare(ResolvedMethod first, ResolvedMethod second) {
            return Ints.compare(first.getArgumentCount(), second.getArgumentCount());
        }
    });
}

From source file:com.sqs.tq.fdc.FileVariantAnalyser.java

private void sortGroups(List<GroupData> groups) {
    Collections.sort(groups, new Comparator<GroupData>() {
        @Override/*from  w w  w  .  j  a v  a 2 s  .c  o  m*/
        public int compare(GroupData o1, GroupData o2) {
            if (o1.count < o2.count) {
                return 1;
            }
            if (o1.count > o2.count) {
                return -1;
            }
            return 0;
        }
    });
}

From source file:controllers.user.UserResumeApp.java

/**
 * ???????? ?// w  w  w .  jav a  2s.  c  om
 */
private static void sortJobExpList(List<JobExp> jobExps) {
    Collections.sort(jobExps, new Comparator<JobExp>() {
        public int compare(JobExp o1, JobExp o2) {
            if (o1 != null && o2 != null && o1.getEndYear() != null && o2.getEndYear() != null
                    && o1.getEndMonth() != null && o2.getEndMonth() != null) {
                if (StringUtils.isBlank(o2.getEndYear()) || StringUtils.equals(o2.getEndYear(), "")) {
                    return 1;
                }
                if (StringUtils.isBlank(o1.getEndYear()) || StringUtils.equals(o1.getEndYear(), "")) {
                    return -1;
                }
                int result = Integer.valueOf(o2.getEndYear()) - Integer.valueOf(o1.getEndYear());
                if (result == 0) {
                    if (StringUtils.isBlank(o2.getEndMonth())) {
                        return 1;
                    }
                    if (StringUtils.isBlank(o1.getEndMonth())) {
                        return -1;
                    }
                    int result2 = Integer.valueOf(o2.getEndMonth()) - Integer.valueOf(o1.getEndMonth());
                    if (result2 == 0) {
                        int result3 = Integer.valueOf(o2.getBeginYear()) - Integer.valueOf(o1.getBeginYear());
                        if (result3 == 0) {
                            return Integer.valueOf(o2.getBeginMonth()) - Integer.valueOf(o1.getBeginMonth());
                        } else {
                            return result3;
                        }
                    } else {
                        return result2;
                    }
                } else {
                    return result;
                }
            }
            return 0;
        }

    });
}

From source file:de.tor.tribes.util.report.ReportManager.java

@Override
public String[] getGroups() {
    String[] groups = super.getGroups();
    Arrays.sort(groups, new Comparator<String>() {

        @Override//w  w  w. j a v a 2s.co m
        public int compare(String o1, String o2) {
            if (o1.equals(DEFAULT_GROUP) || o1.equals(FARM_SET)) {
                return -1;
            } else if (o2.equals(DEFAULT_GROUP) || o2.equals(FARM_SET)) {
                return 1;
            } else {
                return String.CASE_INSENSITIVE_ORDER.compare(o1, o2);
            }
        }
    });
    return groups;
}

From source file:es.logongas.ix3.rule.impl.RuleEngineImpl.java

@Override
public void fireConstraintRules(Object rulesObject, RuleContext<T> ruleContext, Class<?>... groups)
        throws BusinessException {
    List<Method> methods = getRuleMethods(rulesObject, ConstraintRule.class);
    List<BusinessMessage> businessMessages = new ArrayList<BusinessMessage>();

    Collections.sort(methods, new Comparator<Method>() {

        @Override/*from  ww w  .j a  v a 2 s .co m*/
        public int compare(Method method1, Method method2) {
            ConstraintRule constraintRule1 = method1.getAnnotation(ConstraintRule.class);
            ConstraintRule constraintRule2 = method2.getAnnotation(ConstraintRule.class);

            if (constraintRule1.priority() == constraintRule2.priority()) {
                return 0;
            } else if (constraintRule1.priority() > constraintRule2.priority()) {
                return 1;
            } else if (constraintRule1.priority() < constraintRule2.priority()) {
                return -1;
            } else {
                throw new RuntimeException("Error de lgica");
            }

        }

    });

    for (Method method : methods) {
        ConstraintRule constraintRule = method.getAnnotation(ConstraintRule.class);

        if (isExecuteConstrainRule(constraintRule, groups)) {
            try {
                int numArgs = method.getParameterTypes().length;
                boolean result;
                if (numArgs == 0) {
                    result = (Boolean) method.invoke(rulesObject);
                } else if (numArgs == 1) {
                    Class argumenType = method.getParameterTypes()[0];

                    if (RuleContext.class.isAssignableFrom(argumenType) == false) {
                        throw new RuntimeException("El mtodo " + method.getName()
                                + " debe tener el nico argumento del tipo:" + RuleContext.class.getName());
                    }

                    result = (Boolean) method.invoke(rulesObject, ruleContext);

                } else {
                    throw new RuntimeException("El mtodo " + method.getName()
                            + " solo puede tener 0 o 1 argumentos pero tiene:" + numArgs);
                }

                if (result == false) {

                    BusinessMessage businessMessage = getBusinessMessage(constraintRule, ruleContext);
                    businessMessages.add(businessMessage);

                    if (constraintRule.stopOnFail() == true) {
                        break;
                    }
                }

            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (IllegalArgumentException ex) {
                throw new RuntimeException(ex);
            } catch (InvocationTargetException ex) {
                BusinessException businessException = ExceptionUtil.getBusinessExceptionFromThrowable(ex);
                if (businessException != null) {
                    throw businessException;
                } else {
                    throw new RuntimeException(ex);
                }
            }

        }
    }

    if (businessMessages.size() > 0) {
        throw new BusinessException(businessMessages);
    }

}

From source file:net.librec.recommender.content.EFMRecommender.java

/**
 * Sort a map by value./*from w w  w .j  a  v  a2  s .co  m*/
 *
 * @param map the map to sort
 * @param <K> key type
 * @param <V> value type
 * @return a sorted map of the input
 */
protected static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}

From source file:com.c123.billbuddy.dal.Top10ProcessingFeeReducer.java

public ProcessingFee[] reduce(SpaceRemotingResult<ProcessingFee[]>[] results,
        SpaceRemotingInvocation remotingInvocation) throws Exception {

    log.info("Starting Top10MerchantFeeAmountReducer");

    List<ProcessingFee> processingFees = new ArrayList<ProcessingFee>();

    // Each result is an array of events. Each result is from a single partition.        
    for (SpaceRemotingResult<ProcessingFee[]> result : results) {
        if (result.getException() != null) {
            // just log the fact that there was an exception
            log.error("Executor Remoting Exception [" + result.getException() + "]");

            continue;
        }/*from   www .  j a v a  2  s.com*/
        Collections.addAll(processingFees, result.getResult());
    }

    Collections.sort(processingFees, new Comparator<ProcessingFee>() {
        public int compare(ProcessingFee p1, ProcessingFee p2) {
            return p2.getAmount().compareTo(p1.getAmount());
        }
    });

    // If the number of results needed is less than the number of events that were reduced, then
    // return a sublist. Otherwise, return the entire list of events.
    ProcessingFee[] top10ProcessingFee;
    if (processingFees.size() < 10) {
        top10ProcessingFee = new ProcessingFee[processingFees.size()];
        processingFees.toArray(top10ProcessingFee);

    } else {
        top10ProcessingFee = new ProcessingFee[10];
        processingFees.subList(0, 10).toArray(top10ProcessingFee);
    }
    return top10ProcessingFee;
}

From source file:com.redhat.engineering.jenkins.report.plugin.ReportPluginPortlet.java

/**
 * Graph of duration of tests over time.
 *///from   www.  j  a  v  a  2 s . co m
public Graph getSummaryGraph() {
    // The standard equals doesn't work because two LocalDate objects can
    // be differente even if the date is the same (different internal timestamp)
    Comparator<LocalDate> localDateComparator = new Comparator<LocalDate>() {

        @Override
        public int compare(LocalDate d1, LocalDate d2) {
            if (d1.isEqual(d2)) {
                return 0;
            }
            if (d1.isAfter(d2)) {
                return 1;
            }
            return -1;
        }
    };

    // We need a custom comparator for LocalDate objects
    final Map<LocalDate, TestResultAggrSummary> summaries = //new HashMap<LocalDate, TestResultSummary>();
            new TreeMap<LocalDate, TestResultAggrSummary>(localDateComparator);
    LocalDate today = new LocalDate();

    // for each job, for each day, add last build of the day to summary
    for (Job job : getDashboard().getJobs()) {
        Filter filter = job.getAction(ReportPluginProjectAction.class).getInitializedFilter();
        filter.addCombinationFilter(combinationFilter);
        Run run = job.getFirstBuild();

        if (run != null) { // execute only if job has builds
            LocalDate runDay = new LocalDate(run.getTimestamp());
            LocalDate firstDay = (dateRange != 0) ? new LocalDate().minusDays(dateRange) : runDay;

            while (run != null) {
                runDay = new LocalDate(run.getTimestamp());
                Run nextRun = run.getNextBuild();

                if (nextRun != null) {
                    LocalDate nextRunDay = new LocalDate(nextRun.getTimestamp());
                    // skip run before firstDay, but keep if next build is after start date
                    if (!runDay.isBefore(firstDay)
                            || runDay.isBefore(firstDay) && !nextRunDay.isBefore(firstDay)) {
                        // if next run is not the same day, use this test to summarize
                        if (nextRunDay.isAfter(runDay)) {
                            summarize(summaries, run.getAction(ReportPluginBuildAction.class).getTestResults(),
                                    filter, (runDay.isBefore(firstDay) ? firstDay : runDay),
                                    nextRunDay.minusDays(1));
                        }
                    }
                } else {
                    // use this run's test result from last run to today
                    summarize(summaries, run.getAction(ReportPluginBuildAction.class).getTestResults(), filter,
                            (runDay.isBefore(firstDay) ? firstDay : runDay), today);
                }
                run = nextRun;
            }
        }
    }

    return new Graph(-1, getGraphWidth(), getGraphHeight()) {

        protected JFreeChart createGraph() {
            return GraphHelper.createChart(buildDataSet(summaries));
        }
    };
}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.publico.teachersBody.ReadProfessorshipsAndResponsibilitiesByExecutionDegreeAndExecutionPeriod.java

@Atomic
public static List run(String executionDegreeId, Integer semester, Integer teacherType)
        throws FenixServiceException {

    final ExecutionDegree executionDegree = FenixFramework.getDomainObject(executionDegreeId);

    List professorships;/*from  ww  w  .j ava2 s.  c  om*/
    if (semester.intValue() == 0) {
        professorships = Professorship.readByDegreeCurricularPlanAndExecutionYear(
                executionDegree.getDegreeCurricularPlan(), executionDegree.getExecutionYear());
    } else {
        ExecutionSemester executionSemester = executionDegree.getExecutionYear()
                .getExecutionSemesterFor(semester);
        professorships = Professorship.readByDegreeCurricularPlanAndExecutionPeriod(
                executionDegree.getDegreeCurricularPlan(), executionSemester);
    }

    List responsibleFors = getResponsibleForsByDegree(executionDegree);

    List detailedProfessorships = getDetailedProfessorships(professorships, responsibleFors, teacherType);

    // Cleaning out possible null elements inside the list
    Iterator itera = detailedProfessorships.iterator();
    while (itera.hasNext()) {
        Object dp = itera.next();
        if (dp == null) {
            itera.remove();
        }
    }

    Collections.sort(detailedProfessorships, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            DetailedProfessorship detailedProfessorship1 = (DetailedProfessorship) o1;
            DetailedProfessorship detailedProfessorship2 = (DetailedProfessorship) o2;
            int result = detailedProfessorship1.getInfoProfessorship().getInfoExecutionCourse().getExternalId()
                    .compareTo(detailedProfessorship2.getInfoProfessorship().getInfoExecutionCourse()
                            .getExternalId());
            if (result == 0 && (detailedProfessorship1.getResponsibleFor().booleanValue()
                    || detailedProfessorship2.getResponsibleFor().booleanValue())) {
                if (detailedProfessorship1.getResponsibleFor().booleanValue()) {
                    return -1;
                }
                if (detailedProfessorship2.getResponsibleFor().booleanValue()) {
                    return 1;
                }
            }

            return result;
        }

    });

    List result = new ArrayList();
    Iterator iter = detailedProfessorships.iterator();
    List temp = new ArrayList();
    while (iter.hasNext()) {
        DetailedProfessorship detailedProfessorship = (DetailedProfessorship) iter.next();
        if (temp.isEmpty() || ((DetailedProfessorship) temp.get(temp.size() - 1)).getInfoProfessorship()
                .getInfoExecutionCourse()
                .equals(detailedProfessorship.getInfoProfessorship().getInfoExecutionCourse())) {
            temp.add(detailedProfessorship);
        } else {
            result.add(temp);
            temp = new ArrayList();
            temp.add(detailedProfessorship);
        }
    }
    if (!temp.isEmpty()) {
        result.add(temp);
    }
    return result;
}