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.apache.gobblin.service.modules.core.GitConfigMonitorTest.java

@Test(dependsOnMethods = "testDeleteConfig")
public void testForcedPushConfig() throws IOException, GitAPIException, URISyntaxException {
    // push a new config file
    this.testGroupDir.mkdirs();
    this.testFlowFile.createNewFile();
    Files.write("flow.name=testFlow\nflow.group=testGroup\nparam1=value1\n", testFlowFile, Charsets.UTF_8);
    this.testFlowFile2.createNewFile();
    Files.write("flow.name=testFlow2\nflow.group=testGroup\nparam1=value2\n", testFlowFile2, Charsets.UTF_8);

    // add, commit, push
    this.gitForPush.add()
            .addFilepattern(formConfigFilePath(this.testGroupDir.getName(), this.testFlowFile.getName()))
            .call();/*from   w  w  w  .j av  a2  s .c  o  m*/
    this.gitForPush.add()
            .addFilepattern(formConfigFilePath(this.testGroupDir.getName(), this.testFlowFile2.getName()))
            .call();
    this.gitForPush.commit().setMessage("Fifth commit").call();
    this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();

    this.gitConfigMonitor.processGitConfigChanges();

    Collection<Spec> specs = this.flowCatalog.getSpecs();

    Assert.assertTrue(specs.size() == 2);
    List<Spec> specList = Lists.newArrayList(specs);
    specList.sort(new Comparator<Spec>() {
        @Override
        public int compare(Spec o1, Spec o2) {
            return o1.getUri().compareTo(o2.getUri());
        }
    });

    FlowSpec spec = (FlowSpec) specList.get(0);
    Assert.assertEquals(spec.getUri(), new URI("gobblin-flow:/testGroup/testFlow"));
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_NAME_KEY), "testFlow");
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_GROUP_KEY), "testGroup");
    Assert.assertEquals(spec.getConfig().getString("param1"), "value1");

    spec = (FlowSpec) specList.get(1);
    Assert.assertEquals(spec.getUri(), new URI("gobblin-flow:/testGroup/testFlow2"));
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_NAME_KEY), "testFlow2");
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_GROUP_KEY), "testGroup");
    Assert.assertEquals(spec.getConfig().getString("param1"), "value2");

    // go back in time to cause conflict
    this.gitForPush.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD~1").call();
    this.gitForPush.push().setForce(true).setRemote("origin").setRefSpecs(this.masterRefSpec).call();

    // add new files
    this.testGroupDir.mkdirs();
    this.testFlowFile2.createNewFile();
    Files.write("flow.name=testFlow2\nflow.group=testGroup\nparam1=value4\n", testFlowFile2, Charsets.UTF_8);
    this.testFlowFile3.createNewFile();
    Files.write("flow.name=testFlow3\nflow.group=testGroup\nparam1=value5\n", testFlowFile3, Charsets.UTF_8);

    // add, commit, push
    this.gitForPush.add()
            .addFilepattern(formConfigFilePath(this.testGroupDir.getName(), this.testFlowFile2.getName()))
            .call();
    this.gitForPush.add()
            .addFilepattern(formConfigFilePath(this.testGroupDir.getName(), this.testFlowFile3.getName()))
            .call();
    this.gitForPush.commit().setMessage("Sixth commit").call();
    this.gitForPush.push().setRemote("origin").setRefSpecs(this.masterRefSpec).call();

    this.gitConfigMonitor.processGitConfigChanges();

    specs = this.flowCatalog.getSpecs();

    Assert.assertTrue(specs.size() == 2);

    specList = Lists.newArrayList(specs);
    specList.sort(new Comparator<Spec>() {
        @Override
        public int compare(Spec o1, Spec o2) {
            return o1.getUri().compareTo(o2.getUri());
        }
    });

    spec = (FlowSpec) specList.get(0);
    Assert.assertEquals(spec.getUri(), new URI("gobblin-flow:/testGroup/testFlow2"));
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_NAME_KEY), "testFlow2");
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_GROUP_KEY), "testGroup");
    Assert.assertEquals(spec.getConfig().getString("param1"), "value4");

    spec = (FlowSpec) specList.get(1);
    Assert.assertEquals(spec.getUri(), new URI("gobblin-flow:/testGroup/testFlow3"));
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_NAME_KEY), "testFlow3");
    Assert.assertEquals(spec.getConfig().getString(ConfigurationKeys.FLOW_GROUP_KEY), "testGroup");
    Assert.assertEquals(spec.getConfig().getString("param1"), "value5");

    // reset for next test case
    this.gitForPush.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD~4").call();
    this.gitForPush.push().setForce(true).setRemote("origin").setRefSpecs(this.masterRefSpec).call();

    this.gitConfigMonitor.processGitConfigChanges();
    specs = this.flowCatalog.getSpecs();

    Assert.assertTrue(specs.size() == 0);
}

From source file:org.dspace.content.RelationshipServiceImpl.java

@Override
public List<Relationship> findByItem(Context context, Item item) throws SQLException {

    List<Relationship> list = relationshipDAO.findByItem(context, item);

    list.sort((o1, o2) -> {
        int relationshipType = o1.getRelationshipType().getLeftLabel()
                .compareTo(o2.getRelationshipType().getLeftLabel());
        if (relationshipType != 0) {
            return relationshipType;
        } else {// ww w  .jav  a  2s .c  o  m
            if (o1.getLeftItem() == item) {
                return o1.getLeftPlace() - o2.getLeftPlace();
            } else {
                return o1.getRightPlace() - o2.getRightPlace();
            }
        }
    });
    return list;
}

From source file:com.helegris.szorengeteg.ui.forms.TopicFormView.java

/**
 * Loads a (sorted) list of cards into the table. If a card has no ordinal,
 * it will be represented at the bottom.
 *
 * @param cards to be loaded into the table
 *//*from   w w w . j  a  v  a  2 s  .  co m*/
protected void loadRows(List<Card> cards) {
    cards.sort((c1, c2) -> c1.getOrdinal() != null ? c1.getOrdinal() - c2.getOrdinal() : 1);

    cards.stream().forEach(card -> {
        RowForCard row = new RowForCard(this::deleteRow, rowMoveListener, card);
        rows.add(row);
    });
}

From source file:org.beryx.viewreka.fxapp.BundleChooser.java

@SuppressWarnings("deprecation")
@Override/*from w w  w .  j a va  2s .  co m*/
public void initialize(URL location, ResourceBundle resources) {
    check("ttvBundles", ttvBundles);
    check("ttColName", ttColName);
    check("ttColVersion", ttColVersion);
    check("ttColId", ttColId);
    check("ttColDescription", ttColDescription);

    ttvBundles.getColumns().forEach(col -> col.impl_setReorderable(false));

    CatalogManager catalogManager = new CatalogManager(guiSettingsManager.getSettings());
    Map<String, Map<Pair<String, Version>, BundleInfo>> categoryMap = new TreeMap<>();
    catalogManager.getCatalogUrls().forEach(url -> {
        CatalogRepo repo = new CatalogRepo(url, catalogManager.getCatalogCache());
        List<BundleInfo> infoEntries = Collections.emptyList();
        try {
            infoEntries = repo.getEntries();
        } catch (Exception e) {
            Dialogs.error("Cannot read from repository " + repo.getCatalogUrl(), e.getMessage(), e);
        }
        infoEntries.forEach(entry -> entry.getCategories().forEach(category -> {
            Map<Pair<String, Version>, BundleInfo> idMap = categoryMap.get(category);
            if (idMap == null) {
                idMap = new TreeMap<>();
                categoryMap.put(category, idMap);
            }
            String bundleId = entry.getId();
            Version version = entry.getVersion();
            Pair<String, Version> infoPair = new ImmutablePair<>(bundleId, version);
            BundleInfo oldEntry = idMap.get(infoPair);
            if (oldEntry == null) {
                idMap.put(infoPair, entry);
            } else if (entry.getUrl().equals(oldEntry.getUrl())) {
                log.warn("Different URLs for " + entry.getName() + " " + version + ": " + entry.getUrl()
                        + " and " + oldEntry.getUrl());
            }
        }));
    });

    ttvBundles.setRowFactory(item -> new BundleInfoTreeTableRow());
    ttColName.setCellFactory(p -> new BundleInfoNameTreeTableCell<>());

    ttColName.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getValue()));
    ttColVersion.setCellValueFactory(
            param -> new ReadOnlyStringWrapper(param.getValue().getValue().getVersion().toString()));
    ttColId.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue().getId()));
    ttColDescription.setCellValueFactory(
            param -> new ReadOnlyStringWrapper(param.getValue().getValue().getDescription()));

    TreeItem<BundleInfo> root = new TreeItem<>(new NullBundleInfo("Bundles"));
    root.setExpanded(true);
    ttvBundles.setRoot(root);
    ttvBundles.setShowRoot(false);
    categoryMap.entrySet().forEach(categoryEntry -> {
        String category = categoryEntry.getKey();
        TreeItem<BundleInfo> categoryItem = new TreeItem<>(new NullBundleInfo(category));
        categoryItem.setExpanded(true);
        root.getChildren().add(categoryItem);

        List<BundleInfo> bInfo = new ArrayList<>(categoryEntry.getValue().values());
        bInfo.sort((b1, b2) -> {
            int res = b1.getName().compareTo(b2.getName());
            if (res == 0) {
                res = b1.getVersion().compareTo(b2.getVersion());
            }
            return res;
        });
        bInfo.forEach(bundleInfo -> {
            boolean existing = existingBundles.stream()
                    .anyMatch(pair -> bundleInfo.getId().equals(pair.getKey())
                            && bundleInfo.getVersion().equals(pair.getValue()));
            BundleInfoTreeItem bundleItem = new BundleInfoTreeItem(bundleInfo, existing);

            bundleItem.setIndependent(true);
            Pair<String, Version> infoPair = new ImmutablePair<>(bundleInfo.getId(), bundleInfo.getVersion());
            bundleItem.setSelected(initialInfoEntries.stream().anyMatch(
                    entry -> new ImmutablePair<>(entry.getId(), entry.getVersion()).equals(infoPair)));
            bundleItem.selectedProperty()
                    .addListener((obs, oldVal, newVal) -> updateSelection(bundleInfo, newVal));
            categoryItem.getChildren().add(bundleItem);
        });
    });
}

From source file:com.netflix.spinnaker.igor.build.BuildCache.java

public List<String> getTypeaheadResults(String search) {
    List<String> results = new ArrayList<>();
    redisClientDelegate.withKeyScan(baseKey() + ":*:*:*" + search.toUpperCase() + "*:*", 1000,
            page -> results.addAll(page.getResults().stream().map(BuildCache::extractTypeaheadResult)
                    .collect(Collectors.toList())));
    results.sort(Comparator.naturalOrder());
    return results;
}

From source file:com.openshift.internal.restclient.capability.resources.DockerRegistryImageStreamImportCapability.java

private ModelNode findNewestHistoryEntry(ModelNode root) {
    ModelNode history = root.get("history");
    List<ModelNode> entries = history.asList().stream()
            .map(n -> ModelNode.fromJSONString(n.get("v1Compatibility").asString()))
            .collect(Collectors.toList());
    entries.sort(new Comparator<ModelNode>() {

        @Override/*from w  w  w  . j  ava 2 s  .  co m*/
        public int compare(ModelNode one, ModelNode two) {
            String parent1 = one.has(PARENT) ? one.get(PARENT).asString() : null;
            String parent2 = two.has(PARENT) ? one.get(PARENT).asString() : null;
            if (parent1 == null && parent2 != null) {
                return -1;
            } else if (parent1 != null && parent2 == null) {
                return 1;
            } else if (parent1 == null && parent2 == null) {
                return 0; //we should never get here
            }
            String id1 = one.get(ID).asString();
            String id2 = two.get(ID).asString();

            if (parent2.equals(id1)) {
                return -1;
            } else if (parent1.equals(id2)) {
                return 1;
            }

            return 0; //we should never get here
        }
    });

    ModelNode last = entries.get(0);
    LOG.debug("newest history: " + last.toJSONString(false));
    return last;
}

From source file:org.apache.metron.solr.dao.SolrSearchDao.java

protected List<GroupResult> getGroupResults(GroupRequest groupRequest, int index,
        List<PivotField> pivotFields) {
    List<Group> groups = groupRequest.getGroups();
    List<GroupResult> searchResultGroups = new ArrayList<>();
    final GroupOrder groupOrder = groups.get(index).getOrder();
    pivotFields.sort((o1, o2) -> {
        String s1 = groupOrder.getGroupOrderType() == GroupOrderType.TERM ? o1.getValue().toString()
                : Integer.toString(o1.getCount());
        String s2 = groupOrder.getGroupOrderType() == GroupOrderType.TERM ? o2.getValue().toString()
                : Integer.toString(o2.getCount());
        if (groupOrder.getSortOrder() == SortOrder.ASC) {
            return s1.compareTo(s2);
        } else {//w w w  . j ava2  s .c o  m
            return s2.compareTo(s1);
        }
    });

    for (PivotField pivotField : pivotFields) {
        GroupResult groupResult = new GroupResult();
        groupResult.setKey(pivotField.getValue().toString());
        groupResult.setTotal(pivotField.getCount());
        Optional<String> scoreField = groupRequest.getScoreField();
        if (scoreField.isPresent()) {
            groupResult.setScore((Double) pivotField.getFieldStatsInfo().get(scoreField.get()).getSum());
        }
        if (index < groups.size() - 1) {
            groupResult.setGroupedBy(groups.get(index + 1).getField());
            groupResult.setGroupResults(getGroupResults(groupRequest, index + 1, pivotField.getPivot()));
        }
        searchResultGroups.add(groupResult);
    }
    return searchResultGroups;
}

From source file:io.pravega.controller.server.ControllerService.java

private List<SegmentRange> getSegmentRanges(List<Segment> activeSegments, String scope, String stream) {
    List<SegmentRange> listOfSegment = activeSegments.stream().map(segment -> convert(scope, stream, segment))
            .collect(Collectors.toList());
    listOfSegment.sort(Comparator.comparingDouble(SegmentRange::getMinKey));
    return listOfSegment;
}

From source file:org.apache.hadoop.hive.ql.processors.ErasureProcessor.java

private void listPolicies() throws Exception {
    try {/*from   www  .  j av a2  s.c  om*/
        List<HdfsFileErasureCodingPolicy> erasureCodingPolicies = erasureCodingShim
                .getAllErasureCodingPolicies();
        erasureCodingPolicies.sort(nameComparator);
        if (erasureCodingPolicies.isEmpty()) {
            writeTestOutput("No EC Policies present");
        }
        for (HdfsFileErasureCodingPolicy policy : erasureCodingPolicies) {
            writeTestOutput("Policy: " + policy.getName() + " " + policy.getStatus());
        }
    } catch (Exception e) {
        throw new Exception("Cannot do language command: " + e.getMessage());
    }
}

From source file:com.navercorp.pinpoint.web.controller.ScatterChartController.java

private ModelAndView selectFilterScatterData(String applicationName, Range range, int xGroupUnit,
        int yGroupUnit, int limit, boolean backwardDirection, String filterText, int version) {
    final LimitedScanResult<List<TransactionId>> limitedScanResult = flow
            .selectTraceIdsFromApplicationTraceIndex(applicationName, range, limit, backwardDirection);

    final List<TransactionId> transactionIdList = limitedScanResult.getScanData();
    logger.trace("submitted transactionId count={}", transactionIdList.size());

    boolean requestComplete = transactionIdList.size() < limit;

    transactionIdList.sort(TransactionIdComparator.INSTANCE);
    Filter<SpanBo> filter = filterBuilder.build(filterText);

    ModelAndView mv;//w  w  w  . ja va 2  s.c om
    if (version == 1) {
        ScatterData scatterData = scatter.selectScatterData(transactionIdList, applicationName, range,
                xGroupUnit, yGroupUnit, filter);
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "getScatterData range scan(limited:{}, backwardDirection:{}) from ~ to:{} ~ {}, limited:{}, filterDataSize:{}",
                    limit, backwardDirection, DateUtils.longToDateStr(range.getFrom()),
                    DateUtils.longToDateStr(range.getTo()),
                    DateUtils.longToDateStr(limitedScanResult.getLimitedTime()), transactionIdList.size());
        }

        mv = createScatterDataV1(scatterData, requestComplete);
    } else {
        mv = new ModelAndView();
    }

    mv.addObject("currentServerTime", new ServerTime().getCurrentServerTime());
    mv.addObject("from", range.getFrom());
    mv.addObject("to", range.getTo());
    return mv;
}