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:de.dentrassi.pm.storage.web.channel.ChannelController.java

@Secured(false)
@RequestMapping(value = "/channel/{channelId}/viewPlain", method = RequestMethod.GET)
@HttpConstraint(PERMIT)/*from w  w w  .j av a  2  s .  co m*/
public ModelAndView viewPlain(@PathVariable("channelId") final String channelId) {
    final ModelAndView result = new ModelAndView("channel/view");

    try {
        this.channelService.access(By.id(channelId), ReadableChannel.class, (channel) -> {

            final List<ArtifactInformation> sortedArtifacts = new ArrayList<>(
                    channel.getContext().getArtifacts());
            sortedArtifacts.sort(Comparator.comparing(ArtifactInformation::getId)); // FIXME: change to name

            result.put("channel", channel.getInformation());
            result.put("sortedArtifacts", sortedArtifacts);

        });
    } catch (final ChannelNotFoundException e) {
        return CommonController.createNotFound("channel", channelId);
    }

    return result;
}

From source file:org.apache.zeppelin.notebook.Notebook.java

public List<NoteInfo> getNotesInfo(Set<String> userAndRoles) {
    final Set<String> entities = Sets.newHashSet();
    if (userAndRoles != null) {
        entities.addAll(userAndRoles);/*from   w ww  . j  a v a  2 s. co  m*/
    }
    String homescreenNoteId = conf.getString(ConfVars.ZEPPELIN_NOTEBOOK_HOMESCREEN);
    boolean hideHomeScreenNotebookFromList = conf.getBoolean(ConfVars.ZEPPELIN_NOTEBOOK_HOMESCREEN_HIDE);

    synchronized (noteManager.getNotesInfo()) {
        List<NoteInfo> notesInfo = noteManager.getNotesInfo().entrySet().stream()
                .filter(entry -> notebookAuthorization.isReader(entry.getKey(), entities)
                        && ((!hideHomeScreenNotebookFromList) || ((hideHomeScreenNotebookFromList)
                                && !entry.getKey().equals(homescreenNoteId))))
                .map(entry -> new NoteInfo(entry.getKey(), entry.getValue())).collect(Collectors.toList());

        notesInfo.sort((note1, note2) -> {
            String name1 = note1.getId();
            if (note1.getPath() != null) {
                name1 = note1.getPath();
            }
            String name2 = note2.getId();
            if (note2.getPath() != null) {
                name2 = note2.getPath();
            }
            return name1.compareTo(name2);
        });
        return notesInfo;
    }
}

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

@Override
public void updatePlaceInRelationship(Context context, Relationship relationship, boolean isCreation)
        throws SQLException, AuthorizeException {
    Item leftItem = relationship.getLeftItem();
    List<Relationship> leftRelationships = findByItemAndRelationshipType(context, leftItem,
            relationship.getRelationshipType(), true);
    Item rightItem = relationship.getRightItem();
    List<Relationship> rightRelationships = findByItemAndRelationshipType(context, rightItem,
            relationship.getRelationshipType(), false);

    context.turnOffAuthorisationSystem();
    //If useForPlace for the leftlabel is false for the relationshipType,
    // we need to sort the relationships here based on leftplace.
    if (!virtualMetadataPopulator.isUseForPlaceTrueForRelationshipType(relationship.getRelationshipType(),
            true)) {//  w  ww  .  j  a  v  a 2s  . c om
        if (!leftRelationships.isEmpty()) {
            leftRelationships.sort(Comparator.comparingInt(Relationship::getLeftPlace));
            for (int i = 0; i < leftRelationships.size(); i++) {
                leftRelationships.get(i).setLeftPlace(i);
            }
            relationship.setLeftPlace(leftRelationships.size());
        } else {
            relationship.setLeftPlace(0);
        }
    } else {
        updateItem(context, leftItem);

    }

    //If useForPlace for the rightLabel is false for the relationshipType,
    // we need to sort the relationships here based on the rightplace.
    if (!virtualMetadataPopulator.isUseForPlaceTrueForRelationshipType(relationship.getRelationshipType(),
            false)) {
        if (!rightRelationships.isEmpty()) {
            rightRelationships.sort(Comparator.comparingInt(Relationship::getRightPlace));
            for (int i = 0; i < rightRelationships.size(); i++) {
                rightRelationships.get(i).setRightPlace(i);
            }
            relationship.setRightPlace(rightRelationships.size());
        } else {
            relationship.setRightPlace(0);
        }

    } else {
        updateItem(context, rightItem);

    }

    if (isCreation) {
        handleCreationPlaces(context, relationship);
    }
    context.restoreAuthSystemState();

}

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

public Map<String, Object> prepareExperimentFeatures(Experiment experiment,
        ExperimentFeature experimentFeature) {
    ExperimentsController.TasksResult result = new ExperimentsController.TasksResult();
    if (true)//from w  ww  .j  a  va2s  .  c  o m
        throw new IllegalStateException("Not implemented yet");
    //        result.items = taskRepository.findByIsCompletedIsTrueAndFeatureId(Consts.PAGE_REQUEST_10_REC, experimentFeature.getId());

    HyperParamResult hyperParamResult = new HyperParamResult();
    for (ExperimentHyperParams hyperParam : experiment.getHyperParams()) {
        ExperimentUtils.NumberOfVariants variants = ExperimentUtils.getNumberOfVariants(hyperParam.getValues());
        HyperParamList list = new HyperParamList(hyperParam.getKey());
        for (String value : variants.values) {
            list.getList().add(new HyperParamElement(value, false));
        }
        if (list.getList().isEmpty()) {
            list.getList().add(new HyperParamElement("<Error value>", false));
        }
        hyperParamResult.getElements().add(list);
    }

    MetricsResult metricsResult = new MetricsResult();
    List<Map<String, BigDecimal>> values = new ArrayList<>();

    if (true)
        throw new IllegalStateException("Not implemented yet");
    List<Task> seqs = null;
    //        List<Task> seqs = taskRepository.findByIsCompletedIsTrueAndFeatureId(experimentFeature.getId());
    for (Task seq : seqs) {
        MetricValues metricValues = MetricsUtils.getValues(MetricsUtils.to(seq.metrics));
        if (metricValues == null) {
            continue;
        }
        for (Map.Entry<String, BigDecimal> entry : metricValues.values.entrySet()) {
            metricsResult.metricNames.add(entry.getKey());
        }
        values.add(metricValues.values);
    }

    List<MetricElement> elements = new ArrayList<>();
    for (Map<String, BigDecimal> value : values) {
        MetricElement element = new MetricElement();
        for (String metricName : metricsResult.metricNames) {
            BigDecimalHolder holder = new BigDecimalHolder();
            holder.value = value.get(metricName);
            element.values.add(holder);
        }
        elements.add(element);
    }
    elements.sort(MetricElement::compare);

    metricsResult.metrics.addAll(elements.subList(0, Math.min(20, elements.size())));

    Map<String, Object> map = new HashMap<>();
    map.put("metrics", metricsResult);
    map.put("params", hyperParamResult);
    map.put("result", result);
    map.put("experiment", experiment);
    map.put("feature", experimentFeature);
    map.put("consoleResult", new ExperimentsController.ConsoleResult());

    return map;
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

public static List<File> gatherLegacyCanidates(File mcDir) {
    List<File> list = new ArrayList<>();

    @SuppressWarnings("unchecked")
    Map<String, String> args = (Map<String, String>) Launch.blackboard.get("launchArgs");
    String extraMods = args.get("--mods");
    if (extraMods != null) {
        FMLLog.log.info("Found mods from the command line:");
        for (String mod : extraMods.split(",")) {
            File file = new File(mcDir, mod);
            if (!file.exists()) {
                FMLLog.log.info("  Failed to find mod file {} ({})", mod, file.getAbsolutePath());
            } else if (!list.contains(file)) {
                FMLLog.log.debug("  Adding {} ({}) to the mod list", mod, file.getAbsolutePath());
                list.add(file);//ww  w  .jav  a 2  s.com
            } else if (!list.contains(file)) {
                FMLLog.log.debug("  Duplicte command line mod detected {} ({})", mod, file.getAbsolutePath());
            }
        }
    }

    for (String dir : new String[] { "mods", "mods" + File.separatorChar + ForgeVersion.mcVersion }) {
        File base = new File(mcDir, dir);
        if (!base.isDirectory() || !base.exists())
            continue;

        FMLLog.log.info("Searching {} for mods", base.getAbsolutePath());
        for (File f : base.listFiles(MOD_FILENAME_FILTER)) {
            if (!list.contains(f)) {
                FMLLog.log.debug("  Adding {} to the mod list", f.getName());
                list.add(f);
            }
        }
    }

    ModList memory = ModList.cache.get("MEMORY");
    if (!ENABLE_AUTO_MOD_MOVEMENT && memory != null && memory.getRepository() != null)
        memory.getRepository().filterLegacy(list);

    list.sort(FILE_NAME_SORTER_INSENSITVE);
    return list;
}

From source file:bwem.map.MapInitializerImpl.java

/**
 * 1) Fill in and sort DeltasByAscendingAltitude
 *///  w w  w  . j a  v  a  2 s  .com
@Override
public List<MutablePair<WalkPosition, Altitude>> getSortedDeltasByAscendingAltitude(final int mapWalkTileWidth,
        final int mapWalkTileHeight, int altitudeScale) {
    final int range = Math.max(mapWalkTileWidth, mapWalkTileHeight) / 2 + 3; // should suffice for maps with no Sea.

    final List<MutablePair<WalkPosition, Altitude>> deltasByAscendingAltitude = new ArrayList<>();

    for (int dy = 0; dy <= range; ++dy) {
        for (int dx = dy; dx <= range; ++dx) { // Only consider 1/8 of possible deltas. Other ones obtained by symmetry.
            if (dx != 0 || dy != 0) {
                deltasByAscendingAltitude.add(new MutablePair<>(new WalkPosition(dx, dy),
                        new Altitude((int) Math.round(Utils.norm(dx, dy) * altitudeScale))));
            }
        }
    }

    deltasByAscendingAltitude.sort(new PairGenericAltitudeComparator<>());

    return deltasByAscendingAltitude;
}

From source file:org.cgiar.ccafs.marlo.action.powb.PowbCollaborationAction.java

public List<LocElement> loadLocations() {
    List<LocElement> locElements = locElementManager.findAll().stream()
            .filter(c -> c.getLocElementType().getId().longValue() == 2).collect(Collectors.toList());
    locElements.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));
    for (LocElement locElement : locElements) {
        this.loadLocElementsRelations(locElement);
    }/*from w ww . j  av a2 s . com*/

    List<LocElement> locElementsToRet = new ArrayList<>();

    for (LocElement locElement : locElements) {
        if (!locElement.getProjects().isEmpty()) {
            locElementsToRet.add(locElement);
        }
    }
    return locElementsToRet;
}

From source file:com.antsdb.saltedfish.sql.meta.MetadataService.java

private void loadColumns(Transaction trx, TableMeta tableMeta) {
    GTable table = this.orca.getStroageEngine().getTable(Orca.SYSNS, TABLEID_SYSCOLUMN);
    List<ColumnMeta> list = new ArrayList<>();
    for (RowIterator ii = table.scan(trx.getTrxId(), trx.getTrxTs()); ii.next();) {
        long pRow = ii.getRowPointer();
        if (pRow == 0)
            break;
        SlowRow i = SlowRow.fromRowPointer(this.orca.getSpaceManager(), pRow);
        ColumnMeta columnMeta = new ColumnMeta(this.orca.getTypeFactory(), i);
        if (!UberUtil.safeEqual(tableMeta.getNamespace(), columnMeta.getNamespace())) {
            continue;
        }/* ww w.ja v a 2 s.  co m*/
        if (!UberUtil.safeEqual(tableMeta.getTableName(), columnMeta.getTableName())) {
            continue;
        }
        list.add(columnMeta);
    }
    list.sort((col1, col2) -> {
        float delta = col1.getSequence() - col2.getSequence();
        if (delta > 0) {
            return 1;
        } else if (delta < 0) {
            return -1;
        } else {
            return 0;
        }
    });
    tableMeta.setColumns(list);
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

/**
 * The role parameter is ignored for Bitbucket Server.
 *//*from  www  .j  ava 2 s  .c o m*/
@NonNull
@Override
public List<BitbucketServerRepository> getRepositories(@CheckForNull UserRoleInRepository role)
        throws IOException, InterruptedException {
    UriTemplate template = UriTemplate.fromTemplate(API_REPOSITORIES_PATH).set("owner", getUserCentricOwner());

    List<BitbucketServerRepository> repositories;
    try {
        repositories = getResources(template, BitbucketServerRepositories.class);
    } catch (FileNotFoundException e) {
        return new ArrayList<>();
    }
    repositories.sort(Comparator.comparing(BitbucketServerRepository::getRepositoryName));

    return repositories;
}

From source file:com.devnexus.ting.core.service.impl.BusinessServiceImpl.java

@Override
public Dashboard generateDashBoardForSignUp(EventSignup signUp) {
    Dashboard dashboard = new Dashboard();

    List<RegistrationDetails> orders = registrationDao.findPurchasedForEvent(signUp.getEvent());
    orders.sort((order1, order2) -> {
        return order1.getCreatedDate().compareTo(order2.getCreatedDate());
    });//from  ww  w . ja  v  a  2s .c  om

    orders.stream().forEach((order) -> {
        dashboard.addOrder(order);
    });

    orders = registrationDao.findIncompletePaypalOrdersForEvent(signUp.getEvent());
    orders.sort((order1, order2) -> {
        return order1.getCreatedDate().compareTo(order2.getCreatedDate());
    });

    orders.stream().forEach((order) -> {
        dashboard.addInCompletePaypalOrders(order);
    });

    orders = registrationDao.findOrdersRequestingInvoiceForEvent(signUp.getEvent());
    orders.sort((order1, order2) -> {
        return order1.getCreatedDate().compareTo(order2.getCreatedDate());
    });

    orders.stream().forEach((order) -> {
        dashboard.addOrdersRequestingInvoice(order);
    });

    Map<Long, TicketGroup> ticketIdToGroup = new HashMap<>();
    Map<TicketGroup, Integer> ticketGroupCount = new HashMap<>();

    for (RegistrationDetails order : dashboard.getOrders()) {
        for (TicketOrderDetail ticketOrder : order.getOrderDetails()) {
            Long ticketGroupId = ticketOrder.getTicketGroup();
            ticketIdToGroup.computeIfAbsent(ticketGroupId, (id) -> {
                return getTicketGroup(id);
            });
            TicketGroup group = ticketIdToGroup.get(ticketGroupId);
            int count = ticketGroupCount.getOrDefault(group, 0);
            ticketGroupCount.put(group, count + 1);
        }
    }

    for (Map.Entry<TicketGroup, Integer> entry : ticketGroupCount.entrySet()) {
        dashboard.addSale(entry.getKey(), entry.getValue());
    }

    return dashboard;
}