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:com.hortonworks.registries.schemaregistry.state.SchemaVersionLifecycleStates.java

public static void transitionToEnableState(SchemaVersionLifecycleContext context)
        throws SchemaNotFoundException, IncompatibleSchemaException, SchemaLifecycleException,
        SchemaBranchNotFoundException {//from w  w w  . ja  v a2 s  . c  om
    Long schemaVersionId = context.getSchemaVersionId();
    SchemaVersionService schemaVersionService = context.getSchemaVersionService();

    SchemaMetadataInfo schemaMetadataInfo = schemaVersionService.getSchemaMetadata(schemaVersionId);
    SchemaMetadata schemaMetadata = schemaMetadataInfo.getSchemaMetadata();
    String schemaName = schemaMetadata.getName();
    SchemaValidationLevel validationLevel = schemaMetadata.getValidationLevel();

    SchemaVersionInfo schemaVersionInfo = schemaVersionService.getSchemaVersionInfo(schemaVersionId);
    int schemaVersion = schemaVersionInfo.getVersion();
    String schemaText = schemaVersionInfo.getSchemaText();
    List<SchemaVersionInfo> allEnabledSchemaVersions = schemaVersionService
            .getAllSchemaVersions(SchemaBranch.MASTER_BRANCH, schemaName).stream()
            .filter(x -> SchemaVersionLifecycleStates.ENABLED.getId().equals(x.getStateId()))
            .collect(Collectors.toList());

    if (!allEnabledSchemaVersions.isEmpty()) {
        if (validationLevel.equals(SchemaValidationLevel.ALL)) {
            for (SchemaVersionInfo curSchemaVersionInfo : allEnabledSchemaVersions) {
                int curVersion = curSchemaVersionInfo.getVersion();
                if (curVersion < schemaVersion) {
                    checkCompatibility(schemaVersionService, schemaMetadata, schemaText,
                            curSchemaVersionInfo.getSchemaText());
                } else {
                    checkCompatibility(schemaVersionService, schemaMetadata,
                            curSchemaVersionInfo.getSchemaText(), schemaText);
                }
            }
        } else if (validationLevel.equals(SchemaValidationLevel.LATEST)) {
            List<SchemaVersionInfo> sortedSchemaVersionInfos = new ArrayList<>(allEnabledSchemaVersions);
            sortedSchemaVersionInfos.sort(Comparator.comparingInt(SchemaVersionInfo::getVersion));
            int i = 0;
            int size = sortedSchemaVersionInfos.size();
            for (; i < size && sortedSchemaVersionInfos.get(i).getVersion() < schemaVersion; i++) {
                String fromSchemaText = sortedSchemaVersionInfos.get(i).getSchemaText();
                checkCompatibility(schemaVersionService, schemaMetadata, schemaText, fromSchemaText);
            }
            for (; i < size && sortedSchemaVersionInfos.get(i).getVersion() > schemaVersion; i++) {
                String toSchemaText = sortedSchemaVersionInfos.get(i).getSchemaText();
                checkCompatibility(schemaVersionService, schemaMetadata, toSchemaText, schemaText);
            }
        }
    }
    context.setState(ENABLED);
    context.updateSchemaVersionState();
}

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

protected static <Solution_> Collection<Object[]> getInputFilesAsParameters(String dataDirName,
        AbstractSolutionImporter solutionImporter) {
    File importDir = new File(CommonApp.determineDataDir(dataDirName), "import");
    List<File> fileList;
    if (solutionImporter.isInputFileDirectory()) {
        // Non recursively
        fileList = new ArrayList<>(Arrays.asList(
                Objects.requireNonNull(importDir.listFiles((FileFilter) DirectoryFileFilter.INSTANCE))));
    } else {/*ww w. j a  v  a2 s . co  m*/
        // recursively
        fileList = new ArrayList<>(
                FileUtils.listFiles(importDir, new String[] { solutionImporter.getInputFileSuffix() }, true));
    }
    fileList.sort(new ProblemFileComparator());
    List<Object[]> filesAsParameters = new ArrayList<>();
    for (File file : fileList) {
        filesAsParameters.add(new Object[] { file });
    }
    return filesAsParameters;
}

From source file:Main.java

public static <E> E setInSortedList(List<E> list, int index, E item, Comparator<? super E> comparator,
        BiPredicate<? super E, ? super E> distincter) {
    if (distincter != null) {
        ListIterator<E> iter = list.listIterator();
        while (iter.hasNext()) {
            int currIndex = iter.nextIndex();
            E currItem = iter.next();/*from ww  w. j  a v a  2  s.  c  o m*/
            if (index != currIndex && distincter.test(currItem, item)) {
                return null;
            }
        }
    }
    E previousItem = list.set(index, item);
    list.sort(comparator);
    return previousItem;
}

From source file:org.apache.cassandra.db.lifecycle.LogFile.java

private static void deleteRecordFiles(LogRecord record) {
    List<File> files = record.getExistingFiles();

    // we sort the files in ascending update time order so that the last update time
    // stays the same even if we only partially delete files, see comment in isInvalid()
    files.sort((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));

    files.forEach(LogTransaction::delete);
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

public static List<ChromiumVersion> getInstalledVersions() {
    Path chromiumRootPath = get(getProperty("user.home")).resolve(".cdp4j");
    if (!Files.exists(chromiumRootPath)) {
        return Collections.emptyList();
    }//from ww w  .  j av  a 2 s  .c om
    try {
        List<ChromiumVersion> list = list(chromiumRootPath).filter(p -> isDirectory(p))
                .filter(p -> p.getFileName().toString().startsWith("chromium-"))
                .map(p -> new ChromiumVersion(parseInt(p.getFileName().toString().split("-")[1])))
                .collect(Collectors.toList());
        list.sort((o1, o2) -> compare(o2.getRevision(), o1.getRevision()));
        return list;
    } catch (IOException e) {
        throw new CdpException(e);
    }
}

From source file:oct.util.Util.java

public static List<LinePoint> findMaxAndMins(List<LinePoint> line) {
    //create list of all positive Y values to get peaks
    ArrayList<LinePoint> convList = new ArrayList<>(line.size());
    line.forEach(p -> {//from   ww  w.  j av  a2  s  .  c o m
        convList.add(new LinePoint(p.getX(), Math.abs(p.getY())));
    });
    //find X values of peaks
    List<LinePoint> peaks = getMaximums(convList);
    //collect peak points
    List<LinePoint> ret = line.parallelStream()
            .filter(p -> peaks.stream().anyMatch(pk -> pk.getX() == p.getX())).collect(Collectors.toList());
    //sort by X position
    ret.sort(Comparator.comparingInt(peak -> peak.getX()));
    return ret;
}

From source file:aiai.ai.launchpad.experiment.ExperimentsController.java

public static void sortSnippetsByType(List<ExperimentSnippet> snippets) {
    snippets.sort(Comparator.comparing(ExperimentSnippet::getType));
}

From source file:objective.taskboard.domain.converter.IssueFieldsExtractor.java

public static List<Changelog> extractChangelog(JiraIssueDto issue) {
    if (issue.getChangelog() == null)
        return emptyList();

    List<Changelog> result = new LinkedList<>();
    issue.getChangelog().forEach(change -> {
        change.getItems().forEach(item -> {
            result.add(new Changelog(change.getAuthor().getName(), item.getField(), item.getFromString(),
                    item.getToString(), item.getTo(), DateTimeUtils.get(change.getCreated())));
        });/*from   ww w . j av  a 2s .c o  m*/
    });
    result.sort((item1, item2) -> item1.timestamp.compareTo(item2.timestamp));
    return result;
}

From source file:oct.util.Util.java

public static List<LinePoint> findPeaksAndVallies(List<LinePoint> line) {
    //first find peaks
    List<LinePoint> peaks = getMaximums(line);
    //create inverse of line to find vallies
    ArrayList<LinePoint> convList = new ArrayList<>(line.size());
    line.forEach(p -> {/* w ww  .  ja v  a2  s  . c  o m*/
        convList.add(new LinePoint(p.getX(), 0D - p.getY()));
    });
    //find X values of vallies
    List<LinePoint> vallies = getMaximums(convList);
    //collect valley points
    List<LinePoint> ret = line.parallelStream()
            .filter(p -> vallies.stream().anyMatch(pk -> pk.getX() == p.getX())).collect(Collectors.toList());
    //sort by X position
    ret.addAll(peaks);
    ret.sort(Comparator.comparingInt(peak -> peak.getX()));
    return ret;
}

From source file:org.ballerinalang.docgen.docs.BallerinaDocGenerator.java

/**
 * API to generate Ballerina API documentation.
 *  @param sourceRoot    project root//w ww  .  j  ava  2  s .  co  m
 * @param output        path to the output directory where the API documentation will be written to.
 * @param packageFilter comma separated list of package names to be filtered from the documentation.
 * @param isNative      whether the given packages are native or not.
 * @param offline       is offline generation
 * @param sources       either the path to the directories where Ballerina source files reside or a
 */
public static void generateApiDocs(String sourceRoot, String output, String packageFilter, boolean isNative,
        boolean offline, String... sources) {
    out.println("docerina: API documentation generation for sources - " + Arrays.toString(sources));
    List<Link> primitives = primitives();

    // generate package docs
    Map<String, PackageDoc> docsMap = generatePackageDocsMap(sourceRoot, packageFilter, isNative, sources,
            offline);

    if (docsMap.size() == 0) {
        out.println("docerina: no module definitions found!");
        return;
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: generating HTML API documentation...");
    }

    // validate output path
    String userDir = System.getProperty("user.dir");
    // If output directory is empty
    if (output == null) {
        output = System.getProperty(BallerinaDocConstants.HTML_OUTPUT_PATH_KEY,
                userDir + File.separator + ProjectDirConstants.TARGET_DIR_NAME + File.separator + "api-docs");
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: creating output directory: " + output);
    }

    try {
        // Create output directory
        Files.createDirectories(Paths.get(output));
    } catch (IOException e) {
        out.println(String.format("docerina: API documentation generation failed. Couldn't create the [output "
                + "directory] %s. Cause: %s", output, e.getMessage()));
        log.error(
                String.format("API documentation generation failed. Couldn't create the [output directory] %s. "
                        + "" + "" + "Cause: %s", output, e.getMessage()),
                e);
        return;
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: successfully created the output directory: " + output);
    }

    // Sort packages by package path
    List<PackageDoc> packageList = new ArrayList<>(docsMap.values());
    packageList.sort(Comparator.comparing(pkg -> pkg.bLangPackage.packageID.toString()));

    // Sort the package names
    List<String> packageNames = new ArrayList<>(docsMap.keySet());
    Collections.sort(packageNames);

    List<Link> packageNameList = PackageName.convertList(packageNames);

    String packageTemplateName = System.getProperty(BallerinaDocConstants.MODULE_TEMPLATE_NAME_KEY, "page");
    String packageToCTemplateName = System.getProperty(BallerinaDocConstants.MODULE_TOC_TEMPLATE_NAME_KEY,
            "toc");

    List<Path> resources = new ArrayList<>();

    //Iterate over the packages to generate the pages
    for (PackageDoc packageDoc : packageList) {

        try {
            BLangPackage bLangPackage = packageDoc.bLangPackage;
            String pkgDescription = packageDoc.description;

            // Sort functions, connectors, structs, type mappers and annotationDefs
            sortPackageConstructs(bLangPackage);

            String packagePath = refinePackagePath(bLangPackage);
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("docerina: starting to generate docs for module: " + packagePath);
            }

            // other normal packages
            Page page = Generator.generatePage(bLangPackage, packageNameList, pkgDescription, primitives);
            String filePath = output + File.separator + packagePath + HTML;
            Writer.writeHtmlDocument(page, packageTemplateName, filePath);

            if (ConfigRegistry.getInstance().getAsBoolean(BallerinaDocConstants.GENERATE_TOC)) {
                // generates ToC into a separate HTML - requirement of Central
                out.println(
                        "docerina: generating toc: " + output + File.separator + packagePath + "-toc" + HTML);
                String tocFilePath = output + File.separator + packagePath + "-toc" + HTML;
                Writer.writeHtmlDocument(page, packageToCTemplateName, tocFilePath);
            }

            if (Names.BUILTIN_PACKAGE.getValue().equals(packagePath)) {
                // primitives are in builtin package
                Page primitivesPage = Generator.generatePageForPrimitives(bLangPackage, packageNameList,
                        primitives);
                String primitivesFilePath = output + File.separator + "primitive-types" + HTML;
                Writer.writeHtmlDocument(primitivesPage, packageTemplateName, primitivesFilePath);
            }

            // collect package resources
            resources.addAll(packageDoc.resources);

            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("docerina: generated docs for module: " + packagePath);
            }
        } catch (IOException e) {
            out.println(String.format("docerina: API documentation generation failed for module %s: %s",
                    packageDoc.bLangPackage.packageID.toString(), e.getMessage()));
            log.error(String.format("API documentation generation failed for %s",
                    packageDoc.bLangPackage.packageID.toString()), e);
        }
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: copying HTML theme into " + output);
    }
    try {
        BallerinaDocUtils.copyResources("docerina-theme", output);
    } catch (IOException e) {
        out.println(String.format("docerina: failed to copy the docerina-theme resource. Cause: %s",
                e.getMessage()));
        log.error("Failed to copy the docerina-theme resource.", e);
    }
    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: successfully copied HTML theme into " + output);
    }

    if (!resources.isEmpty()) {
        String resourcesDir = output + File.separator + "resources";
        File resourcesDirFile = new File(resourcesDir);
        if (BallerinaDocUtils.isDebugEnabled()) {
            out.println("docerina: copying project resources into " + resourcesDir);
        }
        resources.parallelStream().forEach(path -> {
            try {
                FileUtils.copyFileToDirectory(path.toFile(), resourcesDirFile);
            } catch (IOException e) {
                out.println(String.format(
                        "docerina: failed to copy [resource] %s into [resources directory] " + "%s. Cause: %s",
                        path.toString(), resourcesDir, e.getMessage()));
                log.error(String.format(
                        "docerina: failed to copy [resource] %s into [resources directory] " + "%s. Cause: %s",
                        path.toString(), resourcesDir, e.getMessage()), e);
            }
        });
        if (BallerinaDocUtils.isDebugEnabled()) {
            out.println("docerina: successfully copied project resources into " + resourcesDir);
        }
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: generating the index HTML file.");
    }

    try {
        //Generate the index file with the list of all modules
        String indexTemplateName = System.getProperty(BallerinaDocConstants.MODULE_TEMPLATE_NAME_KEY, "index");
        String indexFilePath = output + File.separator + "index" + HTML;
        Writer.writeHtmlDocument(packageNameList, indexTemplateName, indexFilePath);
    } catch (IOException e) {
        out.println(String.format("docerina: failed to create the index.html. Cause: %s", e.getMessage()));
        log.error("Failed to create the index.html file.", e);
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: successfully generated the index HTML file.");
        out.println("docerina: generating the module-list HTML file.");
    }

    try {
        // Generate module-list.html file which prints the list of processed packages
        String pkgListTemplateName = System.getProperty(BallerinaDocConstants.MODULE_LIST_TEMPLATE_NAME_KEY,
                "module-list");

        String pkgListFilePath = output + File.separator + "module-list" + HTML;
        Writer.writeHtmlDocument(packageNameList, pkgListTemplateName, pkgListFilePath);
    } catch (IOException e) {
        out.println(
                String.format("docerina: failed to create the module-list.html. Cause: %s", e.getMessage()));
        log.error("Failed to create the module-list.html file.", e);
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: successfully generated the module-list HTML file.");
    }

    try {
        String zipPath = System.getProperty(BallerinaDocConstants.OUTPUT_ZIP_PATH);
        if (zipPath != null) {
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("docerina: generating the documentation zip file.");
            }
            BallerinaDocUtils.packageToZipFile(output, zipPath);
            if (BallerinaDocUtils.isDebugEnabled()) {
                out.println("docerina: successfully generated the documentation zip file.");
            }
        }
    } catch (IOException e) {
        out.println(String.format("docerina: API documentation zip packaging failed for %s: %s", output,
                e.getMessage()));
        log.error(String.format("API documentation zip packaging failed for %s", output), e);
    }

    if (BallerinaDocUtils.isDebugEnabled()) {
        out.println("docerina: documentation generation is done.");
    }
}