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.haulmont.cuba.gui.app.core.bulk.BulkEditorWindow.java

protected void createDataComponents() {
    if (managedFields.isEmpty()) {
        infoLabel.setValue(getMessage("bulk.noEditableProperties"));
        applyButton.setVisible(false);/* w w w  .  j av  a  2s .com*/
        return;
    }

    GridLayout grid = componentsFactory.createComponent(GridLayout.class);
    grid.setSpacing(true);
    grid.setColumns(4);
    grid.setRows((managedFields.size() + 1) / 2);
    grid.setStyleName("c-bulk-editor-grid");

    contentPane.add(grid);
    grid.setFrame(frame);

    List<ManagedField> editFields = new ArrayList<>(managedFields.values());
    editFields.sort((o1, o2) -> o1.getLocalizedName().compareTo(o2.getLocalizedName()));

    String fieldWidth = themeConstants.get("cuba.gui.BulkEditorWindow.field.width");

    for (ManagedField field : editFields) {
        Label label = componentsFactory.createComponent(Label.class);
        label.setFrame(getFrame());
        label.setValue(field.getLocalizedName());
        label.setAlignment(Alignment.TOP_LEFT);
        label.setStyleName("field-label");
        if (AppConfig.getClientType() == ClientType.DESKTOP) {
            label.setHeight("25px");
        }

        grid.add(label);

        Datasource<Entity> fieldDs = datasource;
        // field owner metaclass is embeddable only if field domain embeddable,
        // so we can check field domain
        if (metadataTools.isEmbeddable(field.getMetaProperty().getDomain())) {
            fieldDs = datasources.get(field.getParentFqn());
        }

        final Field editField = fieldFactory.createField(fieldDs, field.getMetaProperty());
        if (editField != null) {
            editField.setFrame(getFrame());
            editField.setWidth(fieldWidth);

            boolean required = editField.isRequired();

            BoxLayout boxLayout = componentsFactory.createComponent(HBoxLayout.class);
            boxLayout.setFrame(getFrame());
            boxLayout.setSpacing(true);

            boxLayout.add(editField);

            if (!required) {
                final Button clearButton = componentsFactory.createComponent(Button.class);
                clearButton.setFrame(getFrame());
                Action action = new AbstractAction("actions.BulkClear") {
                    @Override
                    public void actionPerform(Component component) {
                        editField.setEnabled(!editField.isEnabled());
                        if (!editField.isEnabled()) {
                            if (editField instanceof ListEditor) {
                                editField.setValue(Collections.EMPTY_LIST);
                            } else {
                                editField.setValue(null);
                            }
                            setIcon("icons/edit.png");
                            clearButton.setDescription(getMessage("bulk.editAttribute"));
                        } else {
                            setIcon("icons/trash.png");
                            clearButton.setDescription(getMessage("bulk.clearAttribute"));
                        }
                    }
                };
                action.setCaption("");
                action.setIcon("icons/trash.png");

                clearButton.setAction(action);
                clearButton.setDescription(getMessage("bulk.clearAttribute"));

                boxLayout.add(clearButton);
            }

            editField.setRequired(false);

            if (editField instanceof ListEditor) {
                editField.setValue(Collections.EMPTY_LIST);
            } else {
                editField.setValue(null);
            }

            if (fieldValidators != null) {
                Field.Validator validator = fieldValidators.get(field.getFqn());
                if (validator != null) {
                    editField.addValidator(validator);
                }
            }

            grid.add(boxLayout);

            dataFields.put(field.getFqn(), editField);
        } else {
            Label unknownLabel = componentsFactory.createComponent(Label.class);
            unknownLabel.setFrame(getFrame());
            grid.add(unknownLabel);
        }
    }

    if (!dataFields.isEmpty()) {
        dataFields.values().iterator().next().requestFocus();
    }
}

From source file:io.kamax.mxisd.invitation.InvitationManager.java

private String findHomeserverForDomain(String domain) {
    Optional<String> entryOpt = dns.findHost(domain);
    if (entryOpt.isPresent()) {
        String entry = entryOpt.get();
        log.info("Found DNS overwrite for {} to {}", domain, entry);
        try {//from  ww  w  . j  a  v  a  2 s .co m
            return new URL(entry).toString();
        } catch (MalformedURLException e) {
            log.warn("Skipping homeserver Federation DNS overwrite for {} - not a valid URL: {}", domain,
                    entry);
        }
    }

    log.debug("Performing SRV lookup for {}", domain);
    String lookupDns = getSrvRecordName(domain);
    log.info("Lookup name: {}", lookupDns);

    try {
        List<SRVRecord> srvRecords = new ArrayList<>();
        Record[] rawRecords = new Lookup(lookupDns, Type.SRV).run();
        if (rawRecords != null && rawRecords.length > 0) {
            for (Record record : rawRecords) {
                if (Type.SRV == record.getType()) {
                    srvRecords.add((SRVRecord) record);
                } else {
                    log.info("Got non-SRV record: {}", record.toString());
                }
            }

            srvRecords.sort(Comparator.comparingInt(SRVRecord::getPriority));
            for (SRVRecord record : srvRecords) {
                log.info("Found SRV record: {}", record.toString());
                return "https://" + record.getTarget().toString(true) + ":" + record.getPort();
            }
        } else {
            log.info("No SRV record for {}", lookupDns);
        }
    } catch (TextParseException e) {
        log.warn("Unable to perform DNS SRV query for {}: {}", lookupDns, e.getMessage());
    }

    log.info("Performing basic lookup using domain name {}", domain);
    return "https://" + domain + ":8448";
}

From source file:io.swagger.api.impl.ToolsApiServiceImpl.java

@Override
public Response toolsGet(String registryId, String registry, String organization, String name, String toolname,
        String description, String author, String offset, Integer limit, SecurityContext securityContext)
        throws NotFoundException {
    final List<Entry> all = new ArrayList<>();
    all.addAll(toolDAO.findAllPublished());
    all.addAll(workflowDAO.findAllPublished());
    all.sort((o1, o2) -> o1.getGitUrl().compareTo(o2.getGitUrl()));

    List<io.swagger.model.Tool> results = new ArrayList<>();
    for (Entry c : all) {
        if (c instanceof Workflow && (registryId != null || registry != null || organization != null
                || name != null || toolname != null)) {
            continue;
        }/*from   w  ww  .j a v a2 s .  c o  m*/

        if (c instanceof Tool) {
            Tool tool = (Tool) c;
            // check each criteria. This sucks. Can we do this better with reflection? Or should we pre-convert?
            if (registryId != null) {
                if (!registryId.contains(tool.getToolPath())) {
                    continue;
                }
            }
            if (registry != null && tool.getRegistry() != null) {
                if (!tool.getRegistry().toString().contains(registry)) {
                    continue;
                }
            }
            if (organization != null && tool.getNamespace() != null) {
                if (!tool.getNamespace().contains(organization)) {
                    continue;
                }
            }
            if (name != null && tool.getName() != null) {
                if (!tool.getName().contains(name)) {
                    continue;
                }
            }
            if (toolname != null && tool.getToolname() != null) {
                if (!tool.getToolname().contains(toolname)) {
                    continue;
                }
            }
        }
        if (description != null && c.getDescription() != null) {
            if (!c.getDescription().contains(description)) {
                continue;
            }
        }
        if (author != null && c.getAuthor() != null) {
            if (!c.getAuthor().contains(author)) {
                continue;
            }
        }
        // if passing, for each container that matches the criteria, convert to standardised format and return
        io.swagger.model.Tool tool = convertContainer2Tool(c).getLeft();
        if (tool != null) {
            results.add(tool);
        }
    }

    if (limit == null) {
        limit = DEFAULT_PAGE_SIZE;
    }
    List<List<io.swagger.model.Tool>> pagedResults = Lists.partition(results, limit);
    int offsetInteger = 0;
    if (offset != null) {
        offsetInteger = Integer.parseInt(offset);
    }
    if (offsetInteger >= pagedResults.size()) {
        results = new ArrayList<>();
    } else {
        results = pagedResults.get(offsetInteger);
    }
    final Response.ResponseBuilder responseBuilder = Response.ok(results);
    responseBuilder.header("current-offset", offset);
    responseBuilder.header("current-limit", limit);
    // construct links to other pages
    try {
        List<String> filters = new ArrayList<>();
        handleParameter(registryId, "id", filters);
        handleParameter(organization, "organization", filters);
        handleParameter(name, "name", filters);
        handleParameter(toolname, "toolname", filters);
        handleParameter(description, "description", filters);
        handleParameter(author, "author", filters);
        handleParameter(registry, "registry", filters);
        handleParameter(limit.toString(), "limit", filters);

        if (offsetInteger + 1 < pagedResults.size()) {
            URI nextPageURI = new URI(config.getScheme(), null, config.getHostname(),
                    Integer.parseInt(config.getPort()), "/api/ga4gh/v1/tools",
                    Joiner.on('&').join(filters) + "&offset=" + (offsetInteger + 1), null);
            responseBuilder.header("next-page", nextPageURI.toURL().toString());
        }
        URI lastPageURI = new URI(config.getScheme(), null, config.getHostname(),
                Integer.parseInt(config.getPort()), "/api/ga4gh/v1/tools",
                Joiner.on('&').join(filters) + "&offset=" + (pagedResults.size() - 1), null);
        responseBuilder.header("last-page", lastPageURI.toURL().toString());

    } catch (URISyntaxException | MalformedURLException e) {
        throw new WebApplicationException("Could not construct page links", HttpStatus.SC_BAD_REQUEST);
    }

    return responseBuilder.build();
}

From source file:org.phoenicis.repository.types.ClasspathRepository.java

private List<CategoryDTO> buildCategories(String typeId, String typeFileName) throws RepositoryException {
    try {/*  w w  w  . ja v a  2  s .  co  m*/
        final String categoryScanClassPath = packagePath + "/" + typeFileName;
        Resource[] resources = resourceResolver.getResources(categoryScanClassPath + "/*");
        final List<CategoryDTO> categoryDTOS = new ArrayList<>();

        for (Resource resource : resources) {
            final String fileName = resource.getFilename();
            if (!"icon.png".equals(fileName) && !"category.json".equals(fileName)) {
                final CategoryDTO category = buildCategory(typeId, typeFileName, fileName);
                if (!category.getApplications().isEmpty()) {
                    categoryDTOS.add(category);
                }
            }
        }

        categoryDTOS.sort(Comparator.comparing(CategoryDTO::getName));
        return categoryDTOS;
    } catch (IOException e) {
        throw new RepositoryException("Could not build categories", e);
    }
}

From source file:org.kitodo.production.helper.metadata.ImageHelper.java

/**
 * Get image files.//from   ww  w. j av a  2  s.c o m
 *
 * @param directory
 *            current folder
 * @return sorted list with strings representing images of process
 */
public List<URI> getImageFiles(URI directory) {
    /* Verzeichnis einlesen */
    List<URI> files = fileService.getSubUris(imageNameFilter, directory);
    ArrayList<URI> finalFiles = new ArrayList<>();
    for (URI file : files) {
        String newURI = file.toString().replace(directory.toString(), "");
        finalFiles.add(URI.create(newURI));
    }

    List<URI> dataList = new ArrayList<>(finalFiles);

    if (!dataList.isEmpty()) {
        List<URI> orderedFileNameList = prepareOrderedFileNameList(dataList);

        if (orderedFileNameList.size() == dataList.size()) {
            return orderedFileNameList;
        } else {
            dataList.sort(new MetadataImageComparator());
            return dataList;
        }
    } else {
        return new ArrayList<>();
    }
}

From source file:org.languagetool.rules.spelling.SpellingCheckRule.java

@Experimental
protected List<String> reorderSuggestions(List<String> suggestions, String word) {
    // WORK IN PROGRESS
    if (languageModel == null) {
        return suggestions;
    }// w w  w . ja  v  a2  s. c o m
    BaseLanguageModel lm = (BaseLanguageModel) languageModel;
    List<Integer> levenshteinDistances = suggestions.stream()
            .map(suggestion -> StringUtils.getLevenshteinDistance(word, suggestion))
            .collect(Collectors.toList());
    List<Long> frequencies = suggestions.stream().map(lm::getCount).collect(Collectors.toList());
    Long frequenciesSum = frequencies.stream().reduce((a, b) -> a + b).orElse(1L);
    List<Float> normalizedFrequencies = frequencies.stream().map(f -> (float) f / frequenciesSum)
            .collect(Collectors.toList());
    System.out.println("frequencies: " + frequencies + " / normalized: " + normalizedFrequencies);

    List<Pair<String, Float>> scoredSuggestions = new ArrayList<>(suggestions.size());
    for (int i = 0; i < suggestions.size(); i++) {
        float score = (1f / normalizedFrequencies.get(i)) * levenshteinDistances.get(i);
        scoredSuggestions.add(Pair.of(suggestions.get(i), score));
    }
    scoredSuggestions.sort(Comparator.comparing(Pair::getRight));

    System.out.println(
            "Before reordering: " + suggestions.subList(0, 5) + " / After: " + scoredSuggestions.subList(0, 5));

    return scoredSuggestions.stream().map(Pair::getLeft).collect(Collectors.toList());
}

From source file:org.springframework.ide.eclipse.boot.wizard.NewSpringBootWizardModel.java

/**
 * Retrieves frequently used dependencies based on currently set default dependencies and the most popular dependencies
 *
 * @param numberOfMostPopular max number of most popular dependencies
 * @return list of frequently used dependencies
 *///  ww  w  .  j  av a 2s. c  o  m
public List<CheckBoxModel<Dependency>> getFrequentlyUsedDependencies(int numberOfMostPopular) {
    List<CheckBoxModel<Dependency>> defaultDependencies = getDefaultDependencies();
    Set<String> defaultDependecyIds = getDefaultDependenciesIds();
    getMostPopular(numberOfMostPopular).stream().filter(checkboxModel -> {
        return !defaultDependecyIds.contains(checkboxModel.getValue().getId());
    }).forEach(defaultDependencies::add);
    // Sort alphbetically
    defaultDependencies.sort(new Comparator<CheckBoxModel<Dependency>>() {
        @Override
        public int compare(CheckBoxModel<Dependency> d1, CheckBoxModel<Dependency> d2) {
            return d1.getLabel().compareTo(d2.getLabel());
        }
    });
    return defaultDependencies;
}

From source file:org.cgiar.ccafs.marlo.action.annualReport.CrossCgiarPartnershipAction.java

public Long firstFlagship() {
    List<LiaisonInstitution> liaisonInstitutions = new ArrayList<>(loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() != null && c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
            .collect(Collectors.toList()));
    liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym));
    long liaisonInstitutionId = liaisonInstitutions.get(0).getId();
    return liaisonInstitutionId;
}

From source file:org.polymap.p4.imports.utils.FileGroupHelper.java

public static void fillFilesList(List<FileDescription> files, String rootFileName, long fileSize,
        List<File> read) {
    Map<String, List<File>> grouped = FileGroupHelper.groupFilesByName(read);
    String localRootFileName = rootFileName;
    if (rootFileName != null) {
        if (files.stream().anyMatch(f -> rootFileName.equals(f.name.get()))) {
            localRootFileName = "_duplicated";
        }//  ww w .ja v  a2s  .  c  o m
    }
    FileDescription root;
    for (String groupName : grouped.keySet()) {
        try {
            List<File> values = grouped.get(groupName);
            Optional<File> shpFile = values.stream().filter(file -> ShapeFileFormats.SHP.getFileExtension()
                    .equalsIgnoreCase(IFileFormat.getFileExtension(file.getName()))).findFirst();
            DbaseFileHeader dbaseHeader = null;
            ShapefileHeader shapeHeader = null;
            if (shpFile.isPresent()) {
                ShpFiles shpFilesPart = new ShpFiles(shpFile.get());
                dbaseHeader = parseDbaseFileHeader(shpFilesPart);
                shapeHeader = parseShapeFile(shpFilesPart);
                ShapeFileRootDescription shapeFileRootDescription = new ShapeFileRootDescription().featureCount
                        .put(dbaseHeader != null ? dbaseHeader.getNumRecords() : -1);
                SimpleFeatureType featureType = parseFeatureType(shpFile.get());
                if (featureType != null) {
                    shapeFileRootDescription.featureType.put(featureType);
                }
                root = shapeFileRootDescription;
            } else {
                root = new FileDescription();
            }
            files.add(root);
            root.groupName.put(groupName);
            if (localRootFileName != null) {
                root.name.put(localRootFileName).format.put(IFileFormat.getKnownFileFormat(localRootFileName));
            }
            if (fileSize != -1) {
                root.size.set(fileSize);
            }
            FileDescription fileDesc;
            values.sort((File file1, File file2) -> file1.getName().compareTo(file2.getName()));
            String encoding = null;
            for (File file : values) {
                ShapeFileFormats format = ShapeFileFormats.getFileFormat(file);
                if (format == ShapeFileFormats.CPG) {
                    try {
                        encoding = FileUtils.readFileToString(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            for (File file : values) {
                ShapeFileFormats format = ShapeFileFormats.getFileFormat(file);
                if (format != null) {
                    if (format == ShapeFileFormats.DBF) {
                        DbfFileDescription dbfFileDesc = new DbfFileDescription();
                        if (encoding != null) {
                            dbfFileDesc.charset.put("UTF-8");
                        }
                        fileDesc = dbfFileDesc;
                    } else if (format == ShapeFileFormats.PRJ) {
                        CoordinateReferenceSystem crs = parseCRS(file);
                        fileDesc = new PrjFileDescription().crs.put(crs);
                    } else if (format == ShapeFileFormats.SHP) {
                        fileDesc = new ShpFileDescription().geometryType
                                .put(shapeHeader != null ? shapeHeader.getShapeType() : null);
                    } else {
                        fileDesc = new ShapeFileDescription();
                    }
                } else {
                    fileDesc = new FileDescription();
                }
                fileDesc.groupName.put(groupName).name.put(file.getName()).file.put(file).size
                        .put(file.length()).format.put(IFileFormat.getKnownFileFormat(file.getName()));
                root.addContainedFile(fileDesc);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.agent.KubernetesV2OnDemandCachingAgent.java

@Override
public CacheResult loadData(ProviderCache providerCache) {
    log.info(getAgentType() + " is starting");
    reloadNamespaces();/*from  w w w. j  a  va  2  s.  c  om*/

    Long start = System.currentTimeMillis();
    Map<KubernetesKind, List<KubernetesManifest>> primaryResource;
    try {
        primaryResource = loadPrimaryResourceList();
    } catch (KubectlJobExecutor.NoResourceTypeException e) {
        log.warn(getAgentType() + ": resource for this caching agent is not supported for this cluster");
        return new DefaultCacheResult(new HashMap<>());
    }

    List<String> primaryKeys = primaryResource.values().stream().flatMap(Collection::stream)
            .map(rs -> objectMapper.convertValue(rs, KubernetesManifest.class))
            .map(mf -> Keys.infrastructure(mf, accountName)).collect(Collectors.toList());

    List<CacheData> keepInOnDemand = new ArrayList<>();
    List<CacheData> evictFromOnDemand = new ArrayList<>();

    providerCache.getAll(ON_DEMAND_TYPE, primaryKeys).forEach(cd -> {
        // can't be a ternary op due to restrictions on non-statement expressions in lambdas
        if (shouldKeepInOnDemand(start, cd)) {
            keepInOnDemand.add(cd);
        } else {
            evictFromOnDemand.add(cd);
        }
        processOnDemandEntry(cd);
    });

    // sort by increasing cache time to ensure newest entries are first
    keepInOnDemand.sort(Comparator.comparing(a -> ((Long) a.getAttributes().get(CACHE_TIME_KEY))));

    // first build the cache result, then decide which entries to overwrite with on demand data
    CacheResult result = buildCacheResult(primaryResource);
    Map<String, Collection<CacheData>> cacheResults = result.getCacheResults();

    for (CacheData onDemandData : keepInOnDemand) {
        String onDemandKey = onDemandData.getId();
        log.info("On demand entry '{}' is overwriting load data entry", onDemandKey);

        String onDemandResultsJson = (String) onDemandData.getAttributes().get(CACHE_RESULTS_KEY);
        Map<String, Collection<CacheData>> onDemandResults;
        try {
            onDemandResults = objectMapper.readValue(onDemandResultsJson,
                    new TypeReference<Map<String, List<DefaultCacheData>>>() {
                    });
        } catch (IOException e) {
            log.error("Failure parsing stored on demand data for '{}'", onDemandKey, e);
            continue;
        }

        mergeCacheResults(cacheResults, onDemandResults);
    }

    cacheResults.put(ON_DEMAND_TYPE, keepInOnDemand);
    Map<String, Collection<String>> evictionResults = new ImmutableMap.Builder<String, Collection<String>>()
            .put(ON_DEMAND_TYPE, evictFromOnDemand.stream().map(CacheData::getId).collect(Collectors.toList()))
            .build();

    return new DefaultCacheResult(cacheResults, evictionResults);
}