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.wso2.security.tools.advisorytool.builders.CustomerSecurityAdvisoryBuilder.java

@Override
public void buildAffectedProductsList() throws AdvisoryToolException {
    List<Product> affectedProductList = new ArrayList<>();
    List<Product> releasedProductList = ProductDataHolder.getInstance().getProductList();
    List<Patch> patchListForAdvisory = getApplicablePatchListForAdvisory(securityAdvisory.getName());

    if (patchListForAdvisory.isEmpty()) {
        throw new AdvisoryToolException(
                "Applicable patch list for the Security Advisory " + securityAdvisory.getName() + " is empty.");
    }//from  w  w  w  .  ja v  a 2 s  . co m

    //affected product map is built with the affected product and version strings
    // (e.g., WSO2 API Manager 2.1.0) in the patch object.
    Map<String, Map<String, Version>> affectedProductMap = generateAffectedProductMapFromApplicablePatches(
            patchListForAdvisory);

    //iterate through the product map and create the product objects list.
    Iterator it = affectedProductMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        for (Product releasedProduct : releasedProductList) {
            if (releasedProduct.getName().equals(pair.getKey())) {

                Product affectedProduct = new Product();

                //getting the product details from the released product list.
                affectedProduct.setName(releasedProduct.getName());
                affectedProduct.setCodeName(releasedProduct.getCodeName());

                Map<String, Version> affectedVersionMap = (Map<String, Version>) pair.getValue();
                Iterator versionIterator = affectedVersionMap.entrySet().iterator();
                List<Version> affectedVersionList = new ArrayList<>();

                while (versionIterator.hasNext()) {
                    Map.Entry versionPair = (Map.Entry) versionIterator.next();
                    affectedVersionList.add((Version) versionPair.getValue());
                    versionIterator.remove();
                }

                affectedVersionList.sort(Comparator.comparing(Version::getVersionNumber));
                affectedProduct.setVersionList(affectedVersionList);
                affectedProductList.add(affectedProduct);
            }
        }
        it.remove();
    }

    affectedProductList.sort(Comparator.comparing(Product::getName));
    securityAdvisory.setAffectedAllProducts(affectedProductList);
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

@NotNull
public <T> Class<? extends T> findMatchingSubclass(Class<T> beanClass, Collection<QName> fields)
        throws SchemaException {
    SchemaRegistry schemaRegistry = prismContext.getSchemaRegistry();
    TypeDefinition typeDef = schemaRegistry.findTypeDefinitionByCompileTimeClass(beanClass,
            TypeDefinition.class);
    if (typeDef == null) {
        throw new SchemaException("No type definition for " + beanClass);
    }/*ww  w. jav  a  2 s . c  om*/
    List<TypeDefinition> subTypes = new ArrayList<>(typeDef.getStaticSubTypes());
    subTypes.sort(Comparator.comparing(TypeDefinition::getInstantiationOrder, nullsLast(naturalOrder())));
    TypeDefinition matchingDefinition = null;
    for (TypeDefinition subType : subTypes) {
        if (matchingDefinition != null && !Objects.equals(matchingDefinition.getInstantiationOrder(),
                subType.getInstantiationOrder())) {
            break; // found something and went to lower orders -> we can stop searching
        }
        if (matches(subType, fields)) {
            if (matchingDefinition != null) {
                throw new SchemaException("Couldn't unambiguously determine a subclass for " + beanClass
                        + " instantiation (fields: " + fields + "). Candidates: " + matchingDefinition + ", "
                        + subType);
            }
            matchingDefinition = subType;
        }
    }
    if (matchingDefinition == null) {
        final int MAX = 5;
        throw new SchemaException("Couldn't find a subclass of " + beanClass + " that would contain fields "
                + fields + ". Considered " + subTypes.subList(0, Math.min(subTypes.size(), MAX))
                + (subTypes.size() >= MAX ? " (...)" : ""));
    }
    //noinspection unchecked
    Class<? extends T> compileTimeClass = (Class<? extends T>) matchingDefinition.getCompileTimeClass();
    if (compileTimeClass != null) {
        return compileTimeClass;
    } else {
        throw new SchemaException("No compile time class defined for " + matchingDefinition);
    }
}

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

@Override
public RepositoryDTO fetchInstallableApplications() {
    try {/* w ww  . j  a  v  a  2 s. com*/
        final List<TypeDTO> typeDTOS = new ArrayList<>();
        Resource[] resources = resourceResolver.getResources(packagePath + "/*");
        for (Resource resource : resources) {
            final TypeDTO type = buildType(resource.getFilename());
            if (!type.getCategories().isEmpty()) {
                typeDTOS.add(type);
            }
        }
        typeDTOS.sort(Comparator.comparing(TypeDTO::getName));

        final RepositoryDTO.Builder repositoryDTOBuilder = new RepositoryDTO.Builder()
                .withName("classpath repository").withTypes(typeDTOS);
        return repositoryDTOBuilder.build();
    } catch (IOException e) {
        LOGGER.warn("Error while reading resource directory", e);
        return new RepositoryDTO.Builder().build();
    }
}

From source file:com.dgtlrepublic.anitomyj.ParserNumber.java

/**
 * Searches for equivalent number in a list of {@code tokens}. e.g 08(114)
 *
 * @param tokens the list of tokens//from w  w  w  . j a v a 2s.co  m
 * @return true if an equivalent number was found
 */
public boolean searchForEquivalentNumbers(List<Result> tokens) {
    for (Result it : tokens) {
        // find number must be isolated
        if (parser.getParserHelper().isTokenIsolated(it.pos) || !isValidEpisodeNumber(it.token.getContent())) {
            continue;
        }

        // Find the first enclosed, non-delimiter token
        Result nextToken = Token.findNextToken(parser.getTokens(), it.pos, kFlagNotDelimiter);
        if (!ParserHelper.isTokenCategory(nextToken, kBracket))
            continue;
        nextToken = Token.findNextToken(parser.getTokens(), nextToken, kFlagEnclosed, kFlagNotDelimiter);
        if (!ParserHelper.isTokenCategory(nextToken, kUnknown))
            continue;

        // Check if it's an isolated number
        if (!parser.getParserHelper().isTokenIsolated(nextToken.pos)
                || !StringHelper.isNumericString(nextToken.token.getContent())
                || !isValidEpisodeNumber(nextToken.token.getContent())) {
            continue;
        }

        List<Token> list = Arrays.asList(it.token, nextToken.token);
        list.sort((o1, o2) -> Integer.compare(StringHelper.stringToInt(o1.getContent()),
                StringHelper.stringToInt(o2.getContent())));
        setEpisodeNumber(list.get(0).getContent(), list.get(0), false);
        setAlternativeEpisodeNumber(list.get(1).getContent(), list.get(1));
        return true;
    }

    return false;
}

From source file:com.ethlo.geodata.GeodataServiceImpl.java

@Override
public Page<GeoLocation> findChildren(long locationId, Pageable pageable) {
    final Node node = nodes.get(locationId);
    final long total = node.getChildren().size();
    final List<Long> ids = node.getChildren().stream().skip(pageable.getOffset()).limit(pageable.getPageSize())
            .map(Node::getId).collect(Collectors.toList());
    final List<GeoLocation> content = findByIds(ids).stream().filter(Objects::nonNull)
            .collect(Collectors.toList());

    content.sort((a, b) -> a.getName().compareTo(b.getName()));
    return new PageImpl<>(content, pageable, total);
}

From source file:com.navercorp.pinpoint.common.server.bo.grpc.GrpcSpanFactory.java

private List<SpanEventBo> buildSpanEventBoList(List<PSpanEvent> spanEventList) {
    if (CollectionUtils.isEmpty(spanEventList)) {
        return new ArrayList<>();
    }//from ww  w .ja v a 2 s  . c  o m
    List<SpanEventBo> spanEventBoList = new ArrayList<>(spanEventList.size());
    SpanEventBo prevSpanEvent = null;
    for (PSpanEvent pSpanEvent : spanEventList) {
        final SpanEventBo spanEventBo = buildSpanEventBo(pSpanEvent, prevSpanEvent);
        if (!spanEventFilter.filter(spanEventBo)) {
            continue;
        }
        spanEventBoList.add(spanEventBo);
        prevSpanEvent = spanEventBo;
    }

    spanEventBoList.sort(SpanEventComparator.INSTANCE);
    return spanEventBoList;
}

From source file:de.micromata.genome.db.jpa.logging.BaseJpaLoggingImpl.java

private void appendLogAttributes(LogEntry lwe, M master) {
    final Collection<BaseLogAttributeDO<M>> attrs = (Collection) master.getAttributes();
    List<BaseLogAttributeDO<M>> sortedAttrs = new ArrayList<>();
    sortedAttrs.addAll(attrs);/*  w ww. j  a  v a2  s  . com*/
    sortedAttrs.sort((first, second) -> sort(first, second));
    String lastAttr = null;
    LogAttribute lastLogAttr = null;
    String notFoundAttrType = null;
    final StringBuilder sb = new StringBuilder();
    for (BaseLogAttributeDO<M> attrDo : sortedAttrs) {
        if (StringUtils.equals(notFoundAttrType, attrDo.getBaseLogAttribute()) == true) {
            continue;
        }
        if (StringUtils.equals(lastAttr, attrDo.getBaseLogAttribute()) == false) {
            lastAttr = attrDo.getBaseLogAttribute();
            if (lastLogAttr != null) {
                lastLogAttr.setValue(sb.toString());

            }
            LogAttributeType type = getAttributeTypeByString(attrDo.getBaseLogAttribute());
            if (type == null) {
                log.warn("LogAttributeType '" + attrDo.getBaseLogAttribute() + "' is not registered");
                notFoundAttrType = attrDo.getBaseLogAttribute();
                continue;
            }

            lastLogAttr = new LogAttribute(type, "");
            lwe.getAttributes().add(lastLogAttr);
            sb.setLength(0);
        }
        sb.append(attrDo.getDatacol1());

    }
    if (lastLogAttr != null) {
        lastLogAttr.setValue(sb.toString());
        lastLogAttr = null;
    }
}

From source file:com.epam.ta.reportportal.core.launch.impl.UpdateLaunchHandler.java

@Override
public LaunchResource mergeLaunches(String projectName, String userName, MergeLaunchesRQ mergeLaunchesRQ) {
    User user = userRepository.findOne(userName);
    Project project = projectRepository.findOne(projectName);
    expect(project, notNull()).verify(PROJECT_NOT_FOUND, projectName);

    Set<String> launchesIds = mergeLaunchesRQ.getLaunches();
    List<Launch> launchesList = launchRepository.find(launchesIds);

    validateMergingLaunches(launchesList, user, project);

    StartLaunchRQ startRQ = new StartLaunchRQ();
    startRQ.setMode(mergeLaunchesRQ.getMode());
    startRQ.setDescription(mergeLaunchesRQ.getDescription());
    startRQ.setName(mergeLaunchesRQ.getName());
    startRQ.setTags(mergeLaunchesRQ.getTags());

    launchesList.sort(Comparator.comparing(Launch::getStartTime));
    startRQ.setStartTime(launchesList.get(0).getStartTime());
    Launch launch = launchBuilder.get().addStartRQ(startRQ).addProject(projectName).addStatus(IN_PROGRESS)
            .addUser(userName).build();//from  ww w  .ja v a  2  s  .  c o  m
    launch.setNumber(launchCounter.getLaunchNumber(launch.getName(), projectName));
    launchRepository.save(launch);

    launch = launchRepository.findOne(launch.getId());
    launch.setEndTime(launchesList.get(launchesList.size() - 1).getEndTime());
    List<TestItem> statisticsBase = updateChildrenOfLaunch(launch.getId(), mergeLaunchesRQ.getLaunches(),
            mergeLaunchesRQ.isExtendSuitesDescription());
    launch.setStatistics(getLaunchStatisticFromItems(statisticsBase));
    launch.setStatus(getStatusFromStatistics(launch.getStatistics()));
    launchRepository.save(launch);

    launchRepository.delete(launchesIds);

    return launchResourceAssembler.toResource(launch);
}

From source file:net.dv8tion.jda.core.entities.impl.GuildImpl.java

@Override
public List<Role> getRoles() {
    List<Role> list = new ArrayList<>(roles.valueCollection());
    list.sort(Comparator.reverseOrder());
    return Collections.unmodifiableList(list);
}

From source file:amp.lib.io.db.Database.java

/**
 * Finds all the SQL files that descend from the given files/directories. Files are sorted as
 * follows: 1. depth-first traversal of directories first 2. SQL files of this directory, sorted
 * by file name. So, to ensure ordering of SQL execution, place dependent files in
 * sub-directories, or name files something like "1_Foo.sql", "2_Bar.sql".
 * @param sqlFiles List of directories/files to search
 * @return all SQL files in the supplied directory tree, sorted as described abobe.
 *///w  ww  .j  a  va2  s . co  m
private List<File> getAllSQLFiles(List<File> sqlFiles) {
    List<File> orderedFiles = new ArrayList<>();
    for (File f : sqlFiles) {
        if (f.isDirectory()) {
            List<File> files = Arrays.asList(f.listFiles());
            files.sort(new Comparator<File>() {
                @Override
                public int compare(File o1, File o2) {
                    return o1.getName().compareTo(o2.getName());
                };
            });
            orderedFiles.addAll(getAllSQLFiles(files));
        }
    }
    for (File f : sqlFiles) {
        if (!f.isDirectory() && f.getName().endsWith(".sql")) {
            orderedFiles.add(f);
        }
    }
    return orderedFiles;
}