Example usage for java.util List sort

List of usage examples for java.util List sort

Introduction

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

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
default void sort(Comparator<? super E> c) 

Source Link

Document

Sorts this list according to the order induced by the specified Comparator .

Usage

From source file:edu.usu.sdl.openstorefront.doc.EntityProcessor.java

public static List<EntityDocModel> processEntites(List<Class> entities) {
    List<EntityDocModel> entityDocModels = new ArrayList<>();

    log.log(Level.FINEST, "Construct Entities");
    for (Class entity : entities) {
        EntityDocModel docModel = createEntityModel(entity);
        addSuperClass(entity.getSuperclass(), docModel);
        for (Class interfaceClass : entity.getInterfaces()) {
            docModel.getImplementedEntities().add(createEntityModel(interfaceClass));
        }//from   w  ww .j  a  v a 2  s.  c  o  m
        entityDocModels.add(docModel);
    }

    entityDocModels.sort((EntityDocModel o1, EntityDocModel o2) -> o1.getName().compareTo(o2.getName()));
    return entityDocModels;
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

/**
 * Helper method to compute list of continuous ranges. For example, two neighbouring key ranges where,
 * range1.high == range2.low then they are considered neighbours.
 * This method reduces input range into distinct continuous blocks.
 * @param input list of key ranges./*w w w  .j a v a2  s  . co  m*/
 * @return reduced list of key ranges.
 */
private static List<AbstractMap.SimpleEntry<Double, Double>> reduce(
        List<AbstractMap.SimpleEntry<Double, Double>> input) {
    List<AbstractMap.SimpleEntry<Double, Double>> ranges = new ArrayList<>(input);
    ranges.sort(Comparator.comparingDouble(AbstractMap.SimpleEntry::getKey));
    List<AbstractMap.SimpleEntry<Double, Double>> result = new ArrayList<>();
    double low = -1.0;
    double high = -1.0;
    for (AbstractMap.SimpleEntry<Double, Double> range : ranges) {
        if (high < range.getKey()) {
            // add previous result and start a new result if prev.high is less than next.low
            if (low != -1.0 && high != -1.0) {
                result.add(new AbstractMap.SimpleEntry<>(low, high));
            }
            low = range.getKey();
            high = range.getValue();
        } else if (high == range.getKey()) {
            // if adjacent (prev.high == next.low) then update only high
            high = range.getValue();
        } else {
            // if prev.high > next.low.
            // [Note: next.low cannot be less than 0] which means prev.high > 0
            assert low >= 0;
            assert high > 0;
            result.add(new AbstractMap.SimpleEntry<>(low, high));
            low = range.getKey();
            high = range.getValue();
        }
    }
    // add the last range
    if (low != -1.0 && high != -1.0) {
        result.add(new AbstractMap.SimpleEntry<>(low, high));
    }
    return result;
}

From source file:org.xlrnet.metadict.core.query.QueryUtil.java

/**
 * Collect all provided monolingual entries from multiple {@link QueryStepResult} and merge them in one list. The
 * corresponding {@link org.xlrnet.metadict.api.query.MonolingualEntry} objects will only be added, if any of the
 * given {@link QueryStepResult} objects contains a {@link org.xlrnet.metadict.api.query.MonolingualQueryResult}.
 * <p>/*from   w w  w  .j  a v a  2s . c om*/
 * As a temporary solution, the collected entries will be automatically sorted by their Levensthein distance to the
 * query string of the first {@link QueryStepResult}.
 *
 * @param queryStepResults
 *         The source from which the monolingual entries should be collected.
 * @return A list of all {@link org.xlrnet.metadict.api.query.MonolingualEntry} objects in the given {@link
 * QueryStepResult} objects.
 */
@NotNull
public static List<MonolingualEntry> collectMonolingualEntries(
        @NotNull Iterable<QueryStepResult> queryStepResults) {
    List<MonolingualEntry> monolingualEntries = new ArrayList<>();
    for (QueryStepResult queryStepResult : queryStepResults) {
        EngineQueryResult engineQueryResult = queryStepResult.getEngineQueryResult();
        if (!(engineQueryResult instanceof MonolingualQueryResult))
            continue;
        monolingualEntries.addAll(((MonolingualQueryResult) engineQueryResult).getMonolingualEntries());
    }

    if (monolingualEntries.size() > 1) {
        String queryString = queryStepResults.iterator().next().getQueryStep().getQueryString();
        Comparator<MonolingualEntry> comparator = new MonolingualLevenstheinComparator(queryString);
        monolingualEntries.sort(comparator);
    }

    return monolingualEntries;
}

From source file:com.evolveum.midpoint.schema.util.WfContextUtil.java

@NotNull
private static List<ApprovalStageDefinitionType> getSortedStages(ApprovalSchemaType schema) {
    List<ApprovalStageDefinitionType> stages = new ArrayList<>(getStages(schema));
    stages.sort(
            Comparator.comparing(stage -> getNumber(stage), Comparator.nullsLast(Comparator.naturalOrder())));
    return stages;
}

From source file:org.optaplanner.examples.common.persistence.OpenDataFilesTest.java

protected static <Solution_> Collection<Object[]> getSolutionFilesAsParameters(CommonApp<Solution_> commonApp) {
    List<File> fileList = new ArrayList<>(0);
    File dataDir = CommonApp.determineDataDir(commonApp.getDataDirName());
    File unsolvedDataDir = new File(dataDir, "unsolved");
    if (!unsolvedDataDir.exists()) {
        throw new IllegalStateException(
                "The directory unsolvedDataDir (" + unsolvedDataDir.getAbsolutePath() + ") does not exist.");
    }//w w  w . j  a  va  2 s  . co  m
    String inputFileExtension = commonApp.createSolutionFileIO().getInputFileExtension();
    fileList.addAll(FileUtils.listFiles(unsolvedDataDir, new String[] { inputFileExtension }, true));
    File solvedDataDir = new File(dataDir, "solved");
    if (solvedDataDir.exists()) {
        String outputFileExtension = commonApp.createSolutionFileIO().getOutputFileExtension();
        fileList.addAll(FileUtils.listFiles(solvedDataDir, new String[] { outputFileExtension }, true));
    }
    fileList.sort(new ProblemFileComparator());
    List<Object[]> filesAsParameters = new ArrayList<>();
    for (File file : fileList) {
        filesAsParameters.add(new Object[] { file });
    }
    return filesAsParameters;
}

From source file:io.github.retz.cli.Launcher.java

private static int doRequest(Client c, String cmd, Configuration conf)
        throws IOException, InterruptedException {
    if (cmd.equals("list")) {
        ListJobResponse r = (ListJobResponse) c.list(64); // TODO: make this CLI argument
        List<Job> jobs = new LinkedList<>();
        jobs.addAll(r.queue());//from  www  .  j av a2  s . c  o  m
        jobs.addAll(r.running());
        jobs.addAll(r.finished());

        TableFormatter formatter = new TableFormatter("TaskId", "State", "Result", "Duration", "AppName",
                "Command", "Scheduled", "Started", "Finished", "Reason");

        jobs.sort((a, b) -> a.id() - b.id());

        for (Job job : jobs) {
            String state = "Queued";
            if (job.finished() != null) {
                state = "Finished";
            } else if (job.started() != null) {
                state = "Started";
            }
            String reason = "-";
            if (job.reason() != null) {
                reason = "'" + job.reason() + "'";
            }
            String duration = "-";
            if (job.started() != null && job.finished() != null) {
                try {
                    duration = Double
                            .toString(TimestampHelper.diffMillisec(job.finished(), job.started()) / 1000.0);
                } catch (java.text.ParseException e) {
                }
            }
            formatter.feed(Integer.toString(job.id()), state, Integer.toString(job.result()), duration,
                    job.appid(), job.cmd(), job.scheduled(), job.started(), job.finished(), reason);
        }
        LOG.info(formatter.titles());
        for (String line : formatter) {
            LOG.info(line);
        }
        return 0;

    } else if (cmd.equals("schedule")) {
        if (!conf.remoteCommand.isPresent()) { // || !conf.applicationTarball.isPresent()) {
            LOG.error("No command specified");
            return -1;
        }
        try {
            Job job = new Job(conf.getAppName().get(), conf.getRemoteCommand().get(), conf.getJobEnv(),
                    conf.getCpu(), conf.getMemMB(), conf.getGPU());
            job.setTrustPVFiles(conf.getTrustPVFiles());
            LOG.info("Sending job {} to App {}", job.cmd(), job.appid());
            Response res = c.schedule(job);
            if (res instanceof ScheduleResponse) {
                ScheduleResponse res1 = (ScheduleResponse) res;
                LOG.info("Job (id={}): {} registered at {}", res1.job().id(), res1.status(),
                        res1.job.scheduled());
                return 0;
            } else {
                LOG.error("Error: " + res.status());
                return -1;
            }
        } catch (IOException e) {
            LOG.error(e.getMessage());

        } catch (InterruptedException e) {
            LOG.error(e.getMessage());

        }

    } else if (cmd.equals("get-job")) {
        if (conf.getJobId().isPresent()) {
            Response res = c.getJob(conf.getJobId().get());
            if (res instanceof GetJobResponse) {
                GetJobResponse getJobResponse = (GetJobResponse) res;

                if (getJobResponse.job().isPresent()) {
                    Job job = getJobResponse.job().get();

                    LOG.info("Job: appid={}, id={}, scheduled={}, cmd='{}'", job.appid(), job.id(),
                            job.scheduled(), job.cmd());
                    LOG.info("\tstarted={}, finished={}, result={}", job.started(), job.finished(),
                            job.result());

                    if (conf.getJobResultDir().isPresent()) {
                        if (conf.getJobResultDir().get().equals("-")) {
                            LOG.info("==== Printing stdout of remote executor ====");
                            Client.catHTTPFile(job.url(), "stdout");
                            LOG.info("==== Printing stderr of remote executor ====");
                            Client.catHTTPFile(job.url(), "stderr");
                            LOG.info("==== Printing stdout-{} of remote executor ====", job.id());
                            Client.catHTTPFile(job.url(), "stdout-" + job.id());
                            LOG.info("==== Printing stderr-{} of remote executor ====", job.id());
                            Client.catHTTPFile(job.url(), "stderr-" + job.id());
                        } else {
                            Client.fetchHTTPFile(job.url(), "stdout", conf.getJobResultDir().get());
                            Client.fetchHTTPFile(job.url(), "stderr", conf.getJobResultDir().get());
                            Client.fetchHTTPFile(job.url(), "stdout-" + job.id(), conf.getJobResultDir().get());
                            Client.fetchHTTPFile(job.url(), "stderr-" + job.id(), conf.getJobResultDir().get());
                        }
                    }
                    return 0;

                } else {
                    LOG.error("No such job: id={}", conf.getJobId());
                }
            } else {
                ErrorResponse errorResponse = (ErrorResponse) res;
                LOG.error("Error: {}", errorResponse.status());
            }
        } else {
            LOG.error("get-job requires job id you want: {} specified", conf.getJobId());
        }

    } else if (cmd.equals("run")) {
        if (!conf.remoteCommand.isPresent()) { // || !conf.applicationTarball.isPresent()) {
            LOG.error("No command specified");
            return -1;
        }
        Job job = new Job(conf.getAppName().get(), conf.getRemoteCommand().get(), conf.getJobEnv(),
                conf.getCpu(), conf.getMemMB(), conf.getGPU());
        job.setTrustPVFiles(conf.getTrustPVFiles());
        LOG.info("Sending job {} to App {}", job.cmd(), job.appid());
        Job result = c.run(job);

        if (result != null) {
            LOG.info("Job result files URL: {}", result.url());

            if (conf.getJobResultDir().isPresent()) {
                if (conf.getJobResultDir().get().equals("-")) {
                    LOG.info("==== Printing stdout of remote executor ====");
                    Client.catHTTPFile(result.url(), "stdout");
                    LOG.info("==== Printing stderr of remote executor ====");
                    Client.catHTTPFile(result.url(), "stderr");
                    LOG.info("==== Printing stdout-{} of remote executor ====", result.id());
                    Client.catHTTPFile(result.url(), "stdout-" + result.id());
                    LOG.info("==== Printing stderr-{} of remote executor ====", result.id());
                    Client.catHTTPFile(result.url(), "stderr-" + result.id());
                } else {
                    Client.fetchHTTPFile(result.url(), "stdout", conf.getJobResultDir().get());
                    Client.fetchHTTPFile(result.url(), "stderr", conf.getJobResultDir().get());
                    Client.fetchHTTPFile(result.url(), "stdout-" + result.id(), conf.getJobResultDir().get());
                    Client.fetchHTTPFile(result.url(), "stderr-" + result.id(), conf.getJobResultDir().get());
                }
            }
            return result.result();
        }

    } else if (cmd.equals("watch")) {
        c.startWatch((watchResponse -> {
            StringBuilder b = new StringBuilder().append("event: ").append(watchResponse.event());

            if (watchResponse.job() != null) {
                b.append(" Job ").append(watchResponse.job().id()).append(" (app=")
                        .append(watchResponse.job().appid()).append(") has ").append(watchResponse.event())
                        .append(" at ");
                if (watchResponse.event().equals("started")) {
                    b.append(watchResponse.job().started());
                    b.append(" cmd=").append(watchResponse.job().cmd());

                } else if (watchResponse.event().equals("scheduled")) {
                    b.append(watchResponse.job().scheduled());
                    b.append(" cmd=").append(watchResponse.job().cmd());

                } else if (watchResponse.event().equals("finished")) {
                    b.append(watchResponse.job().finished());
                    b.append(" result=").append(watchResponse.job().result());
                    b.append(" url=").append(watchResponse.job().url());
                } else {
                    b.append("unknown event(error)");
                }
            }
            LOG.info(b.toString());
            return true;
        }));
        return 0;

    } else if (cmd.equals("load-app")) {
        if (conf.getAppName().isPresent()) {
            if (conf.getFileUris().isEmpty() || conf.getPersistentFileUris().isEmpty()) {
                LOG.warn("No files specified; mesos-execute would rather suite your use case.");
            }
            if (!conf.getPersistentFileUris().isEmpty() && !conf.getDiskMB().isPresent()) {
                LOG.error("Option '-disk' required when persistent files specified");
                return -1;
            }

            LoadAppResponse r = (LoadAppResponse) c.load(conf.getAppName().get(), conf.getPersistentFileUris(),
                    conf.getFileUris(), conf.getDiskMB());
            LOG.info(r.status());
            return 0;
        }
        LOG.error("AppName is required for load-app");

    } else if (cmd.equals("list-app")) {
        ListAppResponse r = (ListAppResponse) c.listApp();
        for (Application a : r.applicationList()) {
            LOG.info("Application {}: fetch: {} persistent ({} MB): {}", a.getAppid(),
                    String.join(" ", a.getFiles()), a.getDiskMB(), String.join(" ", a.getPersistentFiles()));
        }
        return 0;

    } else if (cmd.equals("unload-app")) {
        if (conf.getAppName().isPresent()) {
            UnloadAppResponse res = (UnloadAppResponse) c.unload(conf.getAppName().get());
            if (res.status().equals("ok")) {
                LOG.info("Unload: {}", res.status());
                return 0;
            }
        }
        LOG.error("unload-app requires AppName");

    }
    return -1;
}

From source file:org.neo4j.nlp.impl.util.VectorUtil.java

public static List<LinkedHashMap<String, Object>> getFeatureFrequencyMap(GraphDatabaseService db, String text,
        GraphManager graphManager, DecisionTree<Long> tree) {
    // This method trains a model on a supplied label and text content
    Map<Long, Integer> patternMatchers = tree.traverseByPattern(text);

    // Translate map to phrases
    List<LinkedHashMap<String, Object>> results = patternMatchers.keySet().stream().map(a -> {
        LinkedHashMap<String, Object> linkHashMap = new LinkedHashMap<>();
        linkHashMap.put("feature", a.intValue());
        linkHashMap.put("frequency", patternMatchers.get(a));
        linkHashMap.put("variance", getFeatureMatchDistribution(db, a));
        return linkHashMap;
    }).collect(Collectors.toList());

    results.sort((a, b) -> {
        Integer diff = ((Integer) a.get("frequency")) - ((Integer) b.get("frequency"));
        return diff > 0 ? -1 : diff.equals(0) ? 0 : 1;
    });/*from   ww w.  j  a v a 2 s. com*/

    return results;
}

From source file:com.vgorcinschi.concordiafootballmanager.data.DefaultTrainerService.java

@Override
public List<Trainer> getAllTrainers() {
    List<Trainer> list = this.trainerRepository.getAll();
    list.sort((p1, p2) -> p1.getSalary().compareTo(p2.getSalary()));
    return list;/*from ww  w.  j  a  v  a  2s.  c om*/
}

From source file:eu.jasha.demo.sbtfragments.CityDao.java

public List<City> getAll() {
    List<City> cityList = new ArrayList<>(cities);
    cityList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
    return cityList;
}

From source file:jfix.util.Reflections.java

/**
 * Returns all instanceable (sub-)classes of given type in given package.
 *//*from www .  j a  v  a  2s. c  o m*/
public static <E> E[] find(Class<E> classType, Package pckage) {
    File directory;
    try {
        String name = "/" + pckage.getName().replace('.', '/');
        directory = new File(classType.getResource(name).toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    List<E> result = new ArrayList<>();
    if (directory.exists()) {
        String[] files = directory.list();
        for (int i = 0; i < files.length; i++) {
            if (files[i].endsWith(".class")) {
                String classname = files[i].substring(0, files[i].length() - 6);
                try {
                    Object o = Class.forName(pckage.getName() + "." + classname).newInstance();
                    if (classType.isInstance(o)) {
                        result.add((E) o);
                    }
                } catch (ClassNotFoundException cnfex) {
                    System.err.println(cnfex);
                } catch (InstantiationException iex) {
                } catch (IllegalAccessException iaex) {
                }
            }
        }
    }
    result.sort(new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            return o1.getClass().getSimpleName().compareTo(o2.getClass().getSimpleName());
        }
    });
    return result.toArray((E[]) Array.newInstance(classType, result.size()));
}