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:org.phoenicis.repository.types.ClasspathRepository.java

private List<ApplicationDTO> buildApplications(String typeId, String categoryId, String typeFileName,
        String categoryFileName) throws RepositoryException {
    try {/*from w w  w. ja v  a 2 s  .  c om*/
        final String categoryScanClassPath = packagePath + "/" + typeFileName + "/" + categoryFileName;
        Resource[] resources = resourceResolver.getResources(categoryScanClassPath + "/*");
        final List<ApplicationDTO> applicationDTOS = new ArrayList<>();

        for (Resource resource : resources) {
            final String fileName = resource.getFilename();
            if (!"icon.png".equals(fileName) && !"category.json".equals(fileName)) {
                final ApplicationDTO application = buildApplication(typeId, categoryId, typeFileName,
                        categoryFileName, fileName);
                if (!application.getScripts().isEmpty()) {
                    applicationDTOS.add(application);
                }
            }
        }

        applicationDTOS.sort(Comparator.comparing(ApplicationDTO::getName));
        return applicationDTOS;
    } catch (IOException e) {
        throw new RepositoryException("Could not build applications", e);
    }
}

From source file:com.netflix.metacat.connector.hive.HiveConnectorPartitionService.java

private List<Partition> getPartitions(final QualifiedName tableName, @Nullable final String filter,
        @Nullable final List<String> partitionIds, @Nullable final Sort sort,
        @Nullable final Pageable pageable) {
    final String databasename = tableName.getDatabaseName();
    final String tablename = tableName.getTableName();
    try {/*from  ww  w  .j av  a2s. c  om*/
        final Table table = metacatHiveClient.getTableByName(databasename, tablename);
        List<Partition> partitionList = null;
        if (!Strings.isNullOrEmpty(filter)) {
            partitionList = metacatHiveClient.listPartitionsByFilter(databasename, tablename, filter);
        } else {
            if (partitionIds != null) {
                partitionList = metacatHiveClient.getPartitions(databasename, tablename, partitionIds);
            }
            if (partitionList == null || partitionList.isEmpty()) {
                partitionList = metacatHiveClient.getPartitions(databasename, tablename, null);
            }
        }
        final List<Partition> filteredPartitionList = Lists.newArrayList();
        partitionList.forEach(partition -> {
            final String partitionName = getNameOfPartition(table, partition);
            if (partitionIds == null || partitionIds.contains(partitionName)) {
                filteredPartitionList.add(partition);
            }
        });
        if (sort != null) {
            if (sort.getOrder() == SortOrder.DESC) {
                filteredPartitionList.sort(Collections.reverseOrder());
            } else {
                Collections.sort(filteredPartitionList);
            }
        }
        return ConnectorUtils.paginate(filteredPartitionList, pageable);
    } catch (NoSuchObjectException exception) {
        throw new TableNotFoundException(tableName, exception);
    } catch (MetaException | InvalidObjectException e) {
        throw new InvalidMetaException("Invalid metadata for " + tableName, e);
    } catch (TException e) {
        throw new ConnectorException(String.format("Failed get partitions for hive table %s", tableName), e);
    }
}

From source file:uk.co.jassoft.markets.utils.article.ContentGrabber.java

public Date getPublishedDate(String html) {
    try {//w ww  . j a  va 2s .c o  m
        Document doc = Jsoup.parse(html);

        List<Date> possibleDates = new ArrayList<>();

        for (String selector : getSelectors()) {
            Elements metalinks = doc.select(selector);

            if (metalinks.isEmpty())
                continue;

            Date value = getDateValue(metalinks.get(0).toString());

            if (value != null) {
                return value;
            }

            if (possibleDates.isEmpty()) {
                LOG.info("Date Format Not recognised for [{}]", metalinks.get(0).toString());
                missingDateFormatRepository
                        .save(new MissingDateFormat(metalinks.get(0).toString(), new Date()));
            }
        }

        if (!possibleDates.isEmpty()) {
            if (possibleDates.size() > 1) {
                possibleDates.sort(Date::compareTo);
            }
            return possibleDates.get(possibleDates.size() - 1);
        }

        return null;
    } catch (Exception exception) {
        LOG.error("Failed to get Published Date", exception);
        return null;
    }
}

From source file:no.asgari.civilization.server.action.GameAction.java

public List<ChatDTO> getChat(String pbfId) {
    Preconditions.checkNotNull(pbfId);//from www  . j a  v a 2  s .  co m
    List<Chat> chats = chatCollection.find(DBQuery.is("pbfId", pbfId)).sort(DBSort.desc("created")).toArray();
    if (chats == null) {
        return new ArrayList<>();
    }
    PBF pbf = findPBFById(pbfId);
    Map<String, String> colorMap = pbf.getPlayers().stream()
            .collect(Collectors.toMap(Playerhand::getUsername, (playerhand) -> {
                return (playerhand.getColor() != null) ? playerhand.getColor() : "";
            }));

    List<ChatDTO> chatDTOs = new ArrayList<>(chats.size());
    for (Chat c : chats) {
        chatDTOs.add(new ChatDTO(c.getId(), c.getPbfId(), c.getUsername(), c.getMessage(),
                colorMap.get(c.getUsername()), c.getCreatedInMillis()));
    }

    //Sort newest date first
    chatDTOs.sort((o1, o2) -> -Long.valueOf(o1.getCreated()).compareTo(o2.getCreated()));
    return chatDTOs;
}

From source file:uk.ac.ebi.ep.base.search.EnzymeFinder.java

private List<UniprotEntry> getEnzymesByAccessions(List<String> accessions, String keyword) {

    List<UniprotEntry> enzymeList = new LinkedList<>();

    if (accessions.size() > 0) {
        Pageable pageable = new PageRequest(0, 500, Sort.Direction.ASC, "function", "entryType");
        //Pageable pageable = new PageRequest(0, 50,Sort.Direction.ASC,"function","lastUpdateTimestamp");old impl
        //Page<UniprotEntry> page = service.findEnzymesByAccessions(accessions, pageable);

        //List<UniprotEntry> enzymes = page.getContent().stream().sorted().collect(Collectors.toList());

        List<UniprotEntry> enzymes = service.findEnzymesByAccessions(accessions);
        enzymes.sort(SWISSPROT_FIRST);
        enzymeList = computeUniqueEnzymes(enzymes, keyword);

    }//from  ww w. j a va2 s. co  m

    return enzymeList;

}

From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java

/**
 * This method is invoked when the daily balance button has been toggled
 *
 * @param actionEvent//w w  w.j av a  2s. com
 */
public void dailyBalanceToggled(ActionEvent actionEvent) {
    LocalDateAxis xAxis = new LocalDateAxis();
    NumberAxis yAxis = new NumberAxis();

    final LineChart<LocalDate, Number> lineChart = new LineChart<>(xAxis, yAxis);
    lineChart.setCreateSymbols(false);

    chartFrame.setCenter(lineChart);

    ToggleButton toggle = (ToggleButton) actionEvent.getTarget();
    if (toggle.isSelected()) {
        xAxis.setLabel("Day of year");
        yAxis.setLabel("Balance in Euro");
        lineChart.setTitle("Balance development day by day");

        ValueRange<LocalDate> period = getTransactionOpRange(accountCombo.getValue(), yearCombo.getValue());
        if (period.isEmpty()) {
            return;
        }
        xAxis.setLowerBound(period.from());
        xAxis.setUpperBound(period.to());

        Service<Void> service = new Service<Void>() {

            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {

                    @Override
                    protected Void call() throws Exception {
                        Map<Account, List<Transaction>> transactionMap = getTransactions(
                                accountCombo.getValue(), yearCombo.getValue());

                        transactionMap.entrySet().forEach(entry -> {
                            Account account = entry.getKey();
                            List<Transaction> transactionList = entry.getValue();

                            XYChart.Series<LocalDate, Number> series = new XYChart.Series<>();
                            series.setName(format("%s [%s]", account.toPresentableString(),
                                    account.getFormattedBalance()));

                            // sort transactions by operation value descending
                            transactionList.sort((t1, t2) -> t2.getDtOp().compareTo(t1.getDtOp()));
                            account.calculateStartingBalance(transactionList);
                            series.getData()
                                    .add(new XYChart.Data<>(account.getBalanceDate(), account.getBalance()));

                            // sort transactions by operation value ascending
                            transactionList.sort((t1, t2) -> t1.getDtOp().compareTo(t2.getDtOp()));
                            transactionList.forEach(trx -> {
                                account.calculateCurrentBalance(trx);
                                series.getData().add(
                                        new XYChart.Data<>(account.getBalanceDate(), account.getBalance()));
                            });

                            Platform.runLater(() -> lineChart.getData().add(series));
                        });

                        return null;
                    }
                };
            }
        };
        service.start();
    }
}

From source file:com.haulmont.cuba.gui.data.impl.CollectionPropertyDatasourceImpl.java

protected void doSort() {
    Collection<T> collection = getCollection();
    if (collection == null)
        return;//from  www. ja  v a 2s  .co  m

    List<T> list = new LinkedList<>(collection);
    list.sort(createEntityComparator());
    collection.clear();
    collection.addAll(list);
}

From source file:org.jsweet.input.typescriptdef.visitor.DuplicateMethodsCleaner.java

private Map<FullFunctionDeclaration, List<String>> calculateNames(Set<FullFunctionDeclaration> duplicates,
        Strategy strategy) {//from ww  w .  j av  a  2s .  co  m
    Map<FullFunctionDeclaration, List<String>> nameMatrix = new HashMap<FullFunctionDeclaration, List<String>>();
    List<FullFunctionDeclaration> l = new ArrayList<FullFunctionDeclaration>(duplicates);
    TypeDeclaration highestTypeDeclaration = getHighestSuperType(duplicates);

    for (int paramIndex = 0; paramIndex < l.get(0).function.getParameters().length; paramIndex++) {
        final int i = paramIndex;
        l.sort(new Comparator<FullFunctionDeclaration>() {
            @Override
            public int compare(FullFunctionDeclaration f1, FullFunctionDeclaration f2) {
                int diff = context.getShortTypeNameNoErasure(f1.function.getParameters()[i].getType()).length()
                        - context.getShortTypeNameNoErasure(f2.function.getParameters()[i].getType()).length();
                if (diff == 0) {
                    return context.getShortTypeNameNoErasure(f1.function.getParameters()[i].getType())
                            .compareTo(context
                                    .getShortTypeNameNoErasure(f2.function.getParameters()[i].getType()));
                } else {
                    return diff;
                }
            }
        });

        List<String> names;
        boolean functionalDisambiguation = isFunctionalTypeReference(
                l.get(0).function.getParameters()[i].getType());
        if (functionalDisambiguation) {
            if (!isFunctionalTypeReference(l.get(0).function.getParameters()[i].getType())
                    || context.getShortTypeNameNoErasure(l.get(0).function.getParameters()[i].getType())
                            .equals(context.getShortTypeNameNoErasure(
                                    l.get(l.size() - 1).function.getParameters()[i].getType()))) {
                // no erasure conflict comes form parameter i (by convention
                // we set an empty name)
                names = new ArrayList<String>(Collections.nCopies(l.size(), NO_OVERRIDE));
            } else {
                names = calculateNames(highestTypeDeclaration, strategy, functionalDisambiguation, l,
                        l.get(0).function, i);
            }
        } else {
            if (context.getShortTypeNameNoErasure(l.get(0).function.getParameters()[i].getType()).equals(context
                    .getShortTypeNameNoErasure(l.get(l.size() - 1).function.getParameters()[i].getType()))) {
                // no erasure conflict comes form parameter i (by convention
                // we set an empty name)
                names = new ArrayList<String>(Collections.nCopies(l.size(), NO_OVERRIDE));
            } else {
                names = calculateNames(highestTypeDeclaration, strategy, functionalDisambiguation, l,
                        l.get(0).function, i);
            }
        }
        for (int j = 0; j < l.size(); j++) {
            List<String> paramNames = nameMatrix.get(l.get(j));
            if (paramNames == null) {
                paramNames = new ArrayList<String>();
                nameMatrix.put(l.get(j), paramNames);
            }
            paramNames.add(names.get(j));
        }
    }
    return nameMatrix;
}

From source file:org.springframework.beans.ExtendedBeanInfo.java

private List<Method> findCandidateWriteMethods(MethodDescriptor[] methodDescriptors) {
    List<Method> matches = new ArrayList<>();
    for (MethodDescriptor methodDescriptor : methodDescriptors) {
        Method method = methodDescriptor.getMethod();
        if (isCandidateWriteMethod(method)) {
            matches.add(method);/*from  www  . j a va  2 s  . co  m*/
        }
    }
    // Sort non-void returning write methods to guard against the ill effects of
    // non-deterministic sorting of methods returned from Class#getDeclaredMethods
    // under JDK 7. See http://bugs.sun.com/view_bug.do?bug_id=7023180
    matches.sort((m1, m2) -> m2.toString().compareTo(m1.toString()));
    return matches;
}

From source file:net.thirdy.blackmarket.controls.ModSelectionPane.java

@Override
public void accept(List<ItemType> itemTypes) {
    masterData.clear();//from ww w .  j  a  va 2s  . co  m
    List<ModMapping> modMappings = ModsMapping.getInstance().getModMappings();
    if (!itemTypes.isEmpty()) {
        List<String> itemTypesRaw = itemTypes.stream().map(itemType -> itemType.itemType())
                .collect(Collectors.toList());
        modMappings = modMappings.stream()
                .filter(mm -> mm.getModType() == ModType.PSEUDO || itemTypesRaw.contains(mm.getItemType()))
                .collect(Collectors.toList());
    }

    Comparator<ModMapping> byModType = (m1, m2) -> Integer.valueOf(m1.getModType().ordinal())
            .compareTo(Integer.valueOf(m2.getModType().ordinal()));

    Comparator<ModMapping> byModTypeThenKey = byModType
            .thenComparing((m1, m2) -> m1.getKey().compareTo(m2.getKey()));
    modMappings.sort(byModTypeThenKey);
    masterData.addAll(modMappings);
}