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:alluxio.cli.fs.command.AbstractFileSystemCommand.java

/**
 * Run the command for a particular URI that may contain wildcard in its path.
 *
 * @param wildCardPath an AlluxioURI that may or may not contain a wildcard
 * @param cl object containing the original commandLine
 * @throws AlluxioException//from www  .j  av a  2s . co m
 * @throws IOException
 */
protected void runWildCardCmd(AlluxioURI wildCardPath, CommandLine cl) throws IOException {
    List<AlluxioURI> paths = FileSystemShellUtils.getAlluxioURIs(mFileSystem, wildCardPath);
    if (paths.size() == 0) { // A unified sanity check on the paths
        throw new IOException(wildCardPath + " does not exist.");
    }
    paths.sort(Comparator.comparing(AlluxioURI::getPath));

    List<String> errorMessages = new ArrayList<>();
    for (AlluxioURI path : paths) {
        try {
            runPlainPath(path, cl);
        } catch (AlluxioException | IOException e) {
            errorMessages.add(e.getMessage() != null ? e.getMessage() : e.toString());
        }
    }

    if (errorMessages.size() != 0) {
        throw new IOException(Joiner.on('\n').join(errorMessages));
    }

}

From source file:org.apache.asterix.common.config.ConfigUsageTest.java

public void generateUsage(String startDelim, String midDelim, String endDelim, EnumMap<Column, Boolean> align,
        PrintStream output) {/*from w  w w.j ava2 s  .co  m*/
    ConfigManager configManager = getConfigManager();
    StringBuilder buf = new StringBuilder();

    final Column[] columns = Column.values();
    for (Section section : getSections(configManager)) {
        for (IOption option : getSectionOptions(configManager, section)) {
            for (Column column : columns) {
                if (align.computeIfAbsent(column, c -> false)) {
                    calculateMaxWidth(option, column);
                }
            }
        }
    }
    // output header
    for (Column column : columns) {
        buf.append(column.ordinal() == 0 ? startDelim : midDelim);
        pad(buf, StringUtils.capitalize(column.name().toLowerCase()),
                align.computeIfAbsent(column, c -> false) ? calculateMaxWidth(column, column.name()) : 0);
    }
    buf.append(endDelim).append('\n');

    StringBuilder sepLine = new StringBuilder();
    for (Column column : columns) {
        sepLine.append(column.ordinal() == 0 ? startDelim : midDelim);
        pad(sepLine, "", maxWidths.getOrDefault(column, 0), '-');
    }
    sepLine.append(endDelim).append('\n');
    buf.append(sepLine.toString().replace(' ', '-'));

    for (Section section : getSections(configManager)) {
        List<IOption> options = new ArrayList<>(getSectionOptions(configManager, section));
        options.sort(Comparator.comparing(IOption::ini));
        for (IOption option : options) {
            for (Column column : columns) {
                buf.append(column.ordinal() == 0 ? startDelim : midDelim);
                if (column == Column.SECTION) {
                    center(buf, extractValue(column, option), maxWidths.getOrDefault(column, 0));
                } else {
                    pad(buf, extractValue(column, option), maxWidths.getOrDefault(column, 0));
                }
            }
            buf.append(endDelim).append('\n');
        }
    }
    output.println(buf);
}

From source file:org.opennms.smoketest.topo.GraphMLTopologyIT.java

@Test
public void verifyNavigateToAndBreadcrumbs() {
    topologyUIPage.selectTopologyProvider(() -> LABEL);
    topologyUIPage.findVertex("East Region").contextMenu().click("Navigate To", "Markets (East Region)");

    final ArrayList<TopologyIT.FocusedVertex> marketsVertcies = Lists.newArrayList(
            focusVertex(topologyUIPage, "Acme:markets:", "East 1"),
            focusVertex(topologyUIPage, "Acme:markets:", "East 2"),
            focusVertex(topologyUIPage, "Acme:markets:", "East 3"),
            focusVertex(topologyUIPage, "Acme:markets:", "East 4"));
    assertEquals(marketsVertcies, topologyUIPage.getFocusedVertices());
    assertEquals("Markets", topologyUIPage.getSelectedLayer());
    assertEquals(Lists.newArrayList("regions", "East Region"), topologyUIPage.getBreadcrumbs().getLabels());

    // Click on last element should add all vertices to focus
    topologyUIPage.getFocusedVertices().get(0).removeFromFocus(); // remove an element from focus
    topologyUIPage.getBreadcrumbs().click("East Region");
    assertEquals(marketsVertcies, topologyUIPage.getFocusedVertices());

    // Click on 1st element, should switch layer and add "child" to focus
    topologyUIPage.getBreadcrumbs().click("regions");
    assertEquals(Lists.newArrayList("regions"), topologyUIPage.getBreadcrumbs().getLabels());
    assertEquals(Lists.newArrayList(focusVertex(topologyUIPage, "Acme:regions:", "East Region")),
            topologyUIPage.getFocusedVertices());

    // Click on last element should add all elements to focus
    topologyUIPage.getBreadcrumbs().click("regions");
    List<TopologyIT.FocusedVertex> focusedVertices = topologyUIPage.getFocusedVertices();
    focusedVertices.sort(Comparator.comparing(TopologyIT.FocusedVertex::getNamespace)
            .thenComparing(TopologyIT.FocusedVertex::getLabel));
    assertEquals(Lists.newArrayList(focusVertex(topologyUIPage, "Acme:regions:", "East Region"),
            focusVertex(topologyUIPage, "Acme:regions:", "North Region"),
            focusVertex(topologyUIPage, "Acme:regions:", "South Region"),
            focusVertex(topologyUIPage, "Acme:regions:", "West Region")), focusedVertices); // all elements should be focused
}

From source file:cc.kave.commons.pointsto.evaluation.ProjectTrainValidateEvaluation.java

public void run(Path usageStoresDir) throws IOException {
    reset();//from  w  w w.j  a v a  2s. co  m

    List<ProjectUsageStore> usageStores = getUsageStores(usageStoresDir);
    try {
        List<ICoReTypeName> types = new ArrayList<>(getStoreTypes(usageStores));
        types.sort(new TypeNameComparator());

        for (ICoReTypeName type : types) {
            if (!usageFilter.test(type)) {
                continue;
            }

            evaluateType(type, usageStores);
            for (UsageStore store : usageStores) {
                store.flush();
            }
        }

        printSummary(usageStores.stream().map(store -> store.getName()).collect(Collectors.toList()));
    } finally {
        for (UsageStore store : usageStores) {
            store.close();
        }
    }

    log("Skipped %d types due to insufficient projects\n", skippedNumProjects);
    log("Skipped %d types due to insufficient usages after filtering\n", skippedUsageFilter);
}

From source file:io.github.swagger2markup.internal.component.ParameterTableComponent.java

@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    PathOperation operation = params.operation;
    List<ObjectType> inlineDefinitions = params.inlineDefinitions;
    List<Parameter> parameters = operation.getOperation().getParameters();
    if (config.getParameterOrdering() != null)
        parameters.sort(config.getParameterOrdering());

    // Filter parameters to display in parameters section
    List<Parameter> filteredParameters = parameters.stream().filter(this::filterParameter)
            .collect(Collectors.toList());

    MarkupDocBuilder parametersBuilder = copyMarkupDocBuilder(markupDocBuilder);
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_DESCRIPTION_BEGIN, parametersBuilder, operation));
    if (CollectionUtils.isNotEmpty(filteredParameters)) {
        StringColumn.Builder typeColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(TYPE_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "2");
        StringColumn.Builder nameColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(NAME_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "3");
        StringColumn.Builder descriptionColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "9").putMetaData(TableComponent.HEADER_COLUMN, "true");
        StringColumn.Builder schemaColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(SCHEMA_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "4").putMetaData(TableComponent.HEADER_COLUMN, "true");
        StringColumn.Builder defaultColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(DEFAULT_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "2").putMetaData(TableComponent.HEADER_COLUMN, "true");

        for (Parameter parameter : filteredParameters) {
            ParameterAdapter parameterAdapter = new ParameterAdapter(context, operation, parameter,
                    definitionDocumentResolver);

            inlineDefinitions.addAll(parameterAdapter.getInlineDefinitions());

            typeColumnBuilder.add(parameterAdapter.displayType(markupDocBuilder));
            nameColumnBuilder.add(getParameterNameColumnContent(markupDocBuilder, parameterAdapter));
            descriptionColumnBuilder.add(parameterAdapter.displayDescription(markupDocBuilder));
            schemaColumnBuilder.add(parameterAdapter.displaySchema(markupDocBuilder));
            defaultColumnBuilder.add(parameterAdapter.displayDefaultValue(markupDocBuilder));
        }/*from ww w . j  av a  2 s . c o m*/

        parametersBuilder = tableComponent.apply(parametersBuilder,
                TableComponent.parameters(typeColumnBuilder.build(), nameColumnBuilder.build(),
                        descriptionColumnBuilder.build(), schemaColumnBuilder.build(),
                        defaultColumnBuilder.build()));
    }
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_DESCRIPTION_END, parametersBuilder, operation));
    String parametersContent = parametersBuilder.toString();

    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_PARAMETERS_BEFORE, markupDocBuilder, operation));
    if (isNotBlank(parametersContent)) {
        markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(PARAMETERS));
        markupDocBuilder.text(parametersContent);
    }
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_PARAMETERS_AFTER, markupDocBuilder, operation));

    return markupDocBuilder;
}

From source file:edu.usu.sdl.openstorefront.report.CategoryComponentReport.java

@Override
protected void writeReport() {
    CSVGenerator cvsGenerator = (CSVGenerator) generator;

    String category = AttributeType.DI2E_SVCV4;
    if (StringUtils.isNotBlank(report.getReportOption().getCategory())) {
        category = report.getReportOption().getCategory();
    }//from  w w  w.  j  av a2  s. c  o  m

    //write header
    cvsGenerator.addLine("Category Component Report", sdf.format(TimeUtil.currentDate()));
    cvsGenerator.addLine("Category:" + category);
    cvsGenerator.addLine("");
    cvsGenerator.addLine("Category Label", "Category Description", "Component Name", "Component Description",
            //"Security Classification",
            "Last Update Date");

    //Only grab approved/active components
    AttributeType attributeType = service.getAttributeService().findType(category);
    List<AttributeCode> codes = service.getAttributeService().findCodesForType(category);

    if (Convert.toBoolean(attributeType.getArchitectureFlg())) {
        codes.sort(new AttributeCodeArchComparator<>());
    } else {
        codes.sort(new AttributeCodeComparator<>());
    }

    ComponentAttribute componentAttributeExample = new ComponentAttribute();
    ComponentAttributePk componentAttributePk = new ComponentAttributePk();
    componentAttributePk.setAttributeType(category);
    componentAttributeExample.setActiveStatus(ComponentAttribute.ACTIVE_STATUS);
    componentAttributeExample.setComponentAttributePk(componentAttributePk);

    List<ComponentAttribute> attributes = componentAttributeExample.findByExample();

    Map<String, List<String>> codeComponentMap = new HashMap<>();
    attributes.forEach(attribute -> {
        if (codeComponentMap.containsKey(attribute.getComponentAttributePk().getAttributeCode())) {
            codeComponentMap.get(attribute.getComponentAttributePk().getAttributeCode())
                    .add(attribute.getComponentId());
        } else {
            List<String> componentIds = new ArrayList<>();
            componentIds.add(attribute.getComponentId());
            codeComponentMap.put(attribute.getComponentAttributePk().getAttributeCode(), componentIds);
        }
    });

    Component componentExample = new Component();
    componentExample.setActiveStatus(Component.ACTIVE_STATUS);
    componentExample.setApprovalState(ApprovalStatus.APPROVED);

    List<Component> components = componentExample.findByExample();
    Map<String, Component> componentMap = new HashMap<>();
    components.forEach(component -> {
        componentMap.put(component.getComponentId(), component);
    });

    for (AttributeCode code : codes) {
        cvsGenerator.addLine(code.getLabel(), code.getDescription());

        List<String> componentIds = codeComponentMap.get(code.getAttributeCodePk().getAttributeCode());
        if (componentIds != null) {
            for (String componentId : codeComponentMap.get(code.getAttributeCodePk().getAttributeCode())) {
                Component component = componentMap.get(componentId);
                if (component != null) {
                    cvsGenerator.addLine("", "", component.getName(), component.getDescription(),
                            //component.getSecurityMarkingType(),
                            sdf.format(component.getLastActivityDts()));
                }
            }
        }
    }
}

From source file:org.cgiar.ccafs.marlo.action.json.global.CrpProgramsGlobalUnitAction.java

@Override
public String execute() throws Exception {

    crpPrograms = new ArrayList<>();
    Map<String, Object> crpProgramMap;

    GlobalUnit globalUnit = globalUnitManager.getGlobalUnitById(globalUnitId.longValue());
    if (globalUnit != null) {
        List<CrpProgram> crpPrograms = globalUnit.getCrpPrograms().stream()
                .filter(c -> c.isActive() && c.getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
                .collect(Collectors.toList());
        crpPrograms.sort((p1, p2) -> p1.getAcronym().compareTo(p2.getAcronym()));
        for (CrpProgram crpProgram : crpPrograms) {
            crpProgramMap = new HashMap<String, Object>();
            crpProgramMap.put("id", crpProgram.getId());
            crpProgramMap.put("description", crpProgram.getName());
            crpProgramMap.put("acronym", crpProgram.getAcronym());

            this.crpPrograms.add(crpProgramMap);
        }/* w  ww.  j  a v a2 s.  c  o m*/

    }

    return SUCCESS;
}

From source file:aiai.ai.launchpad.snippet.SnippetService.java

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

From source file:io.druid.segment.realtime.firehose.SqlFirehoseFactoryTest.java

private void assertResult(List<Row> rows, List<String> sqls) {
    Assert.assertEquals(10 * sqls.size(), rows.size());
    rows.sort((r1, r2) -> {
        int c = r1.getTimestamp().compareTo(r2.getTimestamp());
        if (c != 0) {
            return c;
        }//from w  ww.j  a  v a  2  s . co m
        c = Integer.valueOf(r1.getDimension("a").get(0))
                .compareTo(Integer.valueOf(r2.getDimension("a").get(0)));
        if (c != 0) {
            return c;
        }

        return Integer.valueOf(r1.getDimension("b").get(0))
                .compareTo(Integer.valueOf(r2.getDimension("b").get(0)));
    });
    int rowCount = 0;
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < sqls.size(); j++) {
            final Row row = rows.get(rowCount);
            String timestampSt = StringUtils.format("2011-01-12T00:0%s:00.000Z", i);
            Assert.assertEquals(timestampSt, row.getTimestamp().toString());
            Assert.assertEquals(i, Integer.valueOf(row.getDimension("a").get(0)).intValue());
            Assert.assertEquals(i, Integer.valueOf(row.getDimension("b").get(0)).intValue());
            rowCount++;
        }
    }
}

From source file:de.whs.poodle.repositories.McStatisticsRepository.java

public List<McWorksheetResults> getHighscoresForWorksheet(McWorksheet worksheet) {
    // get all students that completed this worksheet
    List<Integer> studentIds = em.createQuery(
            "SELECT id FROM Student "
                    + "WHERE FUNCTION('has_student_completed_mc_worksheet', id, :mcWorksheetId) = TRUE",
            Integer.class).setParameter("mcWorksheetId", worksheet.getMcWorksheetId()).getResultList();

    // get the results
    List<McWorksheetResults> resultsList = studentIds.stream()
            .map(studentId -> getStudentMcWorksheetResults(worksheet, studentId)).collect(Collectors.toList());

    // sort by points
    resultsList.sort((r1, r2) -> r2.getPoints() - r1.getPoints());

    return resultsList;
}