Example usage for java.util LinkedList sort

List of usage examples for java.util LinkedList sort

Introduction

In this page you can find the example usage for java.util LinkedList 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.epsilonlabs.workflow.execution.example.GraphOutput.java

@Override
public void onNext(Object o) {

    // update graph
    Entry<?, ?> entry = (Entry<?, ?>) o;

    String key = entry.getKey().toString();
    String value = entry.getValue().toString();

    if (key.startsWith("[") && key.endsWith("]")) {
        String[] keys = key.split(",");
        for (String key1 : keys) {
            onNext(createEntry(key1, value));
        }//w w w  .  j  a v  a2  s .  c om
        return;
    }

    if (data.containsKey(key)) {
        data.get(key).add(value);
        // dataset.addValue(data.get(key).size(), "null", key);
    } else {
        HashSet<String> ret = new HashSet<>();
        ret.add(value);
        data.put(key, ret);
        // dataset.addValue(data.get(key).size(), "null", key);
    }

    // sort every 100 iterations to avoid flicker
    if (current % 100 == 0)
        dataset.clear();

    LinkedList<Entry<String, HashSet<String>>> list = new LinkedList<>();
    list.addAll(data.entrySet());
    list.sort(new Comparator<Entry<String, HashSet<String>>>() {
        @Override
        public int compare(Entry<String, HashSet<String>> o1, Entry<String, HashSet<String>> o2) {
            return new Integer(o2.getValue().size()).compareTo(o1.getValue().size());
        }
    });

    for (Entry<String, HashSet<String>> e : list)
        dataset.addValue(e.getValue().size(), "null", e.getKey());
    //
    //

    current++;
    if (current % period == 0)
        notifyObserversOfStatusChange("processed " + current + " elements");
}

From source file:sx.blah.discord.handle.impl.obj.Guild.java

@Override
public List<IRole> getRoles() {
    LinkedList<IRole> list = new LinkedList<>(roles.values());
    list.sort((r1, r2) -> {
        int originalPos1 = ((Role) r1).position;
        int originalPos2 = ((Role) r2).position;
        if (originalPos1 == originalPos2) {
            return r2.getCreationDate().compareTo(r1.getCreationDate());
        } else {/*w w  w. ja  v a  2s  .  c o m*/
            return originalPos1 - originalPos2;
        }
    });
    return list;
}

From source file:sx.blah.discord.handle.impl.obj.Guild.java

@Override
public List<IChannel> getChannels() {
    LinkedList<IChannel> list = new LinkedList<>(channels.values());
    list.sort((c1, c2) -> {
        int originalPos1 = ((Channel) c1).position;
        int originalPos2 = ((Channel) c2).position;
        if (originalPos1 == originalPos2) {
            return c2.getCreationDate().compareTo(c1.getCreationDate());
        } else {/*from w  w w .j av a  2 s .c o  m*/
            return originalPos1 - originalPos2;
        }
    });
    return list;
}

From source file:sx.blah.discord.handle.impl.obj.Guild.java

@Override
public List<IVoiceChannel> getVoiceChannels() {
    LinkedList<IVoiceChannel> list = new LinkedList<>(voiceChannels.values());
    list.sort((c1, c2) -> {
        int originalPos1 = ((Channel) c1).position;
        int originalPos2 = ((Channel) c2).position;
        if (originalPos1 == originalPos2) {
            return c2.getCreationDate().compareTo(c1.getCreationDate());
        } else {/*from   www.ja v  a  2s.c  om*/
            return originalPos1 - originalPos2;
        }
    });
    return list;
}

From source file:com.microfocus.application.automation.tools.octane.configuration.JobConfigurationProxy.java

@JavaScriptMethod
public JSONObject loadJobConfigurationFromServer(String instanceId) {
    OctaneClient octaneClient = OctaneSDK.getClientByInstanceId(instanceId);

    JSONObject ret = new JSONObject();
    JSONObject workspaces = new JSONObject();
    JSONArray fieldsMetadata = new JSONArray();
    try {//from   w w w .  j  a v a 2  s.  co m
        boolean isUftJob = false;
        List<CIParameter> parameters = ParameterProcessors.getConfigs(job);
        if (parameters != null) {
            for (CIParameter parameter : parameters) {
                if (parameter != null && parameter.getName() != null && parameter.getName().equals("suiteId")) {
                    isUftJob = true;
                    break;
                }
            }
        }
        ret.put("isUftJob", isUftJob);

        final String jobCiId = JobProcessorFactory.getFlowProcessor(job).getTranslateJobName();
        PipelineContextList pipelineContextList = octaneClient.getPipelineContextService()
                .getJobConfiguration(octaneClient.getInstanceId(), jobCiId);

        if (!pipelineContextList.getData().isEmpty()) {
            Map<Long, List<PipelineContext>> workspacesMap = pipelineContextList.buildWorkspace2PipelinesMap();
            //WORKAROUND BEGIN
            //getting workspaceName - because the workspaceName is not returned from configuration API
            Map<Long, String> relatedWorkspaces = new HashMap<>();
            List<Entity> workspaceList = getWorkspacesById(octaneClient, workspacesMap.keySet());
            for (Entity workspace : workspaceList) {
                relatedWorkspaces.put(Long.parseLong(workspace.getId()), workspace.getName());
            }
            //WORKAROUND END

            Map<Entity, List<PipelineContext>> sortedWorkspacesMap = new TreeMap<>(
                    Comparator.comparing(Entity::getName));
            Comparator<PipelineContext> pipelineComparator = Comparator
                    .comparing(PipelineContext::getContextEntityName);

            //create workspaces JSON Object
            for (Entry<Long, List<PipelineContext>> workspacePipelines : workspacesMap.entrySet()) {
                Entity relatedWorkspace = dtoFactory.newDTO(Entity.class);

                relatedWorkspace.setId(workspacePipelines.getKey().toString());
                relatedWorkspace.setName(relatedWorkspaces.get(workspacePipelines.getKey()));

                JSONObject relatedPipelinesJSON = new JSONObject();

                for (PipelineContext relatedPipeline : workspacePipelines.getValue()) {
                    JSONObject pipelineJSON = fromPipeline(relatedPipeline, relatedWorkspace);
                    enrichPipelineInstanceId(pipelineJSON, instanceId);
                    relatedPipelinesJSON.put(String.valueOf(relatedPipeline.getContextEntityId()),
                            pipelineJSON);
                }
                JSONObject workspaceJSON = new JSONObject();
                workspaceJSON.put("id", relatedWorkspace.getId());
                workspaceJSON.put("name", relatedWorkspace.getName());
                workspaceJSON.put("pipelines", relatedPipelinesJSON);
                workspaces.put(String.valueOf(relatedWorkspace.getId()), workspaceJSON);

                //inserting this workspace into sortedMap (sorted by workspaceName and by pipelineName, so that we can pick first workspace and its first pipeline as preselected values
                LinkedList<PipelineContext> workspacePipelinesList = new LinkedList<>(
                        workspacePipelines.getValue());
                workspacePipelinesList.sort(pipelineComparator);
                sortedWorkspacesMap.put(relatedWorkspace, workspacePipelinesList);
            }

            //create currentPipeline JSON Object
            //currently the first pipeline in the first workspace is picked
            Entity preSelectedWorkspace = sortedWorkspacesMap.keySet().iterator().next();
            PipelineContext preSelectedPipeline = sortedWorkspacesMap.get(preSelectedWorkspace).get(0);
            JSONObject preSelectedPipelineJSON = fromPipeline(preSelectedPipeline, preSelectedWorkspace);
            enrichPipelineInstanceId(preSelectedPipelineJSON, instanceId);
            //WORKAROUND BEGIN
            //all metadata have to be loaded in separate REST calls for this pipeline: releaseName, taxonomyNames and listFieldNames are not returned from configuration API
            enrichPipelineInternal(preSelectedPipelineJSON, octaneClient);
            //WORKAROUND END
            ret.put("currentPipeline", preSelectedPipelineJSON);

            //retrieving metadata fields for preselected workspace
            fieldsMetadata = convertToJsonMetadata(getPipelineListNodeFieldsMetadata(octaneClient,
                    Long.parseLong(preSelectedWorkspace.getId())));
        }

        ret.put("workspaces", workspaces);
        ret.put("fieldsMetadata", fieldsMetadata);

    } catch (Exception e) {
        logger.warn("Failed to retrieve job configuration", e);
        return error("Unable to retrieve job configuration");
    }

    return ret;
}

From source file:com.epam.dlab.mongo.DlabResourceTypeDAO.java

/**
 * Update exploratory cost in Mongo DB.//from w  w  w.  j a  va 2s.  co  m
 *
 * @param user            the name of user.
 * @param exploratoryName id of exploratory.
 */
private void updateExploratoryCost(String user, String exploratoryName) {
    LOGGER.debug("Update explorartory {} cost for user {}", exploratoryName, user);
    List<? extends Bson> pipeline = Arrays.asList(
            match(and(eq(FIELD_USER, user), eq(FIELD_EXPLORATORY_NAME, exploratoryName))),
            group(getGrouppingFields(FIELD_DLAB_RESOURCE_ID, ReportLine.FIELD_PRODUCT,
                    ReportLine.FIELD_RESOURCE_TYPE, ReportLine.FIELD_CURRENCY_CODE),
                    sum(ReportLine.FIELD_COST, "$" + ReportLine.FIELD_COST),
                    min(FIELD_USAGE_DATE_START, "$" + ReportLine.FIELD_USAGE_DATE),
                    max(FIELD_USAGE_DATE_END, "$" + ReportLine.FIELD_USAGE_DATE)),
            sort(new Document(FIELD_ID + "." + FIELD_DLAB_RESOURCE_ID, 1)
                    .append(FIELD_ID + "." + ReportLine.FIELD_PRODUCT, 1)));
    AggregateIterable<Document> docs = connection.getCollection(COLLECTION_BILLING).aggregate(pipeline);
    LinkedList<Document> billing = new LinkedList<>();
    ResourceItemList resources = getResourceList();
    Double costTotal = null;
    String currencyCode = null;
    for (Document d : docs) {
        Document id = (Document) d.get(FIELD_ID);
        double cost = BillingCalculationUtils.round(d.getDouble(ReportLine.FIELD_COST), 2);
        costTotal = (costTotal == null ? cost : costTotal + cost);
        if (currencyCode == null) {
            currencyCode = id.getString(ReportLine.FIELD_CURRENCY_CODE);
        }

        Document total = new Document()
                .append(FIELD_RESOURCE_NAME,
                        resources.getById(id.getString(FIELD_DLAB_RESOURCE_ID)).getResourceName())
                .append(ReportLine.FIELD_PRODUCT, id.getString(ReportLine.FIELD_PRODUCT))
                .append(ReportLine.FIELD_RESOURCE_TYPE, id.getString(ReportLine.FIELD_RESOURCE_TYPE))
                .append(ReportLine.FIELD_COST, BillingCalculationUtils.formatDouble(cost))
                .append(ReportLine.FIELD_CURRENCY_CODE, id.getString(ReportLine.FIELD_CURRENCY_CODE))
                .append(FIELD_USAGE_DATE_START, d.getString(FIELD_USAGE_DATE_START))
                .append(FIELD_USAGE_DATE_END, d.getString(FIELD_USAGE_DATE_END));
        billing.add(total);
    }

    LOGGER.debug("Total explorartory {} cost for user {} is {} {}, detail count is {}", exploratoryName, user,
            costTotal, currencyCode, billing.size());
    billing.sort(new BillingComparator());

    MongoCollection<Document> cExploratory = connection.getCollection(COLLECTION_USER_INSTANCES);
    Bson values = Updates.combine(
            Updates.set(ReportLine.FIELD_COST, BillingCalculationUtils.formatDouble(costTotal)),
            Updates.set(FIELD_CURRENCY_CODE, currencyCode),
            Updates.set(COLLECTION_BILLING, (!billing.isEmpty() ? billing : null)));
    cExploratory.updateOne(and(and(eq(FIELD_USER, user), eq(FIELD_EXPLORATORY_NAME, exploratoryName))), values);
}

From source file:org.dspace.app.rest.link.HalLinkService.java

public void addLinks(HALResource halResource, Pageable pageable) throws Exception {
    LinkedList<Link> links = new LinkedList<>();

    List<HalLinkFactory> supportedFactories = getSupportedFactories(halResource);
    for (HalLinkFactory halLinkFactory : supportedFactories) {
        links.addAll(halLinkFactory.getLinksFor(halResource, pageable));
    }/*from  w ww  . j  a v a2s  .co m*/

    links.sort((Link l1, Link l2) -> ObjectUtils.compare(l1.getRel(), l2.getRel()));

    halResource.add(links);

    for (Object obj : halResource.getEmbeddedResources().values()) {
        if (obj instanceof Collection) {
            for (Object subObj : (Collection) obj) {
                if (subObj instanceof HALResource) {
                    addLinks((HALResource) subObj);
                }
            }
        } else if (obj instanceof Map) {
            for (Object subObj : ((Map) obj).values()) {
                if (subObj instanceof HALResource) {
                    addLinks((HALResource) subObj);
                }
            }
        } else if (obj instanceof EmbeddedPage) {
            for (Map.Entry<String, List> pageContent : ((EmbeddedPage) obj).getPageContent().entrySet()) {
                for (Object subObj : CollectionUtils.emptyIfNull(pageContent.getValue())) {
                    if (subObj instanceof HALResource) {
                        addLinks((HALResource) subObj);
                    }
                }
            }
        } else if (obj instanceof HALResource) {
            addLinks((HALResource) obj);
        }
    }
}

From source file:org.edmcouncil.rdf_toolkit.SesameRdfFormatter.java

/** Main method, but throws exceptions for use from inside other Java code. */
public static void run(String[] args) throws Exception {
    URI baseUri = null;//w w  w .  j  a v a  2s  .  c o m
    String baseUriString = "";
    String uriPattern = null;
    String uriReplacement = null;
    boolean useDtdSubset = false;
    boolean inlineBlankNodes = false;
    boolean inferBaseUri = false;
    URI inferredBaseUri = null;
    String[] leadingComments = null;
    String[] trailingComments = null;
    String indent = "\t";
    SesameSortedRDFWriterFactory.StringDataTypeOptions stringDataTypeOption = SesameSortedRDFWriterFactory.StringDataTypeOptions.implicit;

    // Parse the command line options.
    CommandLineParser parser = new BasicParser();
    CommandLine line = parser.parse(options, args);

    // Print out help, if requested.
    if (line.hasOption("h")) {
        usage(options);
        return;
    }

    // Check if required arguments provided.
    if (!line.hasOption("s")) {
        logger.error("No source (input) file specified, nothing to format.  Use --help for help.");
        return;
    }
    if (!line.hasOption("t")) {
        logger.error("No target (target) file specified, cannot format source.  Use --help for help.");
        return;
    }

    // Check if source files exists.
    String sourceFilePath = line.getOptionValue("s");
    File sourceFile = new File(sourceFilePath);
    if (!sourceFile.exists()) {
        logger.error("Source file does not exist: " + sourceFilePath);
        return;
    }
    if (!sourceFile.isFile()) {
        logger.error("Source file is not a file: " + sourceFilePath);
        return;
    }
    if (!sourceFile.canRead()) {
        logger.error("Source file is not readable: " + sourceFilePath);
        return;
    }

    // Check if target file can be written.
    String targetFilePath = line.getOptionValue("t");
    File targetFile = new File(targetFilePath);
    if (targetFile.exists()) {
        if (!targetFile.isFile()) {
            logger.error("Target file is not a file: " + targetFilePath);
            return;
        }
        if (!targetFile.canWrite()) {
            logger.error("Target file is not writable: " + targetFilePath);
            return;
        }
    }

    // Create directory for target file, if required.
    File targetFileDir = targetFile.getParentFile();
    if (targetFileDir != null) {
        targetFileDir.mkdirs();
        if (!targetFileDir.exists()) {
            logger.error("Target file directory could not be created: " + targetFileDir.getAbsolutePath());
            return;
        }
    }

    // Check if a base URI was provided
    try {
        if (line.hasOption("bu")) {
            baseUriString = line.getOptionValue("bu");
            baseUri = new URIImpl(baseUriString);
            if (baseUriString.endsWith("#")) {
                logger.warn("base URI ends in '#', which is unusual: " + baseUriString);
            }
        }
    } catch (Throwable t) {
        baseUri = null;
        baseUriString = "";
    }

    // Check if there is a valid URI pattern/replacement pair
    if (line.hasOption("up")) {
        if (line.hasOption("ur")) {
            if (line.getOptionValue("up").length() < 1) {
                logger.error("A URI pattern cannot be an empty string.  Use --help for help.");
                return;
            }
            uriPattern = line.getOptionValue("up");
            uriReplacement = line.getOptionValue("ur");
        } else {
            logger.error(
                    "If a URI pattern is specified, a URI replacement must also be specified.  Use --help for help.");
            return;
        }
    } else {
        if (line.hasOption("ur")) {
            logger.error(
                    "If a URI replacement is specified, a URI pattern must also be specified.  Use --help for help.");
            return;
        }
    }

    // Check if a DTD subset should be used for namespace shortening in XML
    if (line.hasOption("dtd")) {
        useDtdSubset = true;
    }

    // Check if blank nodes should be rendered inline
    if (line.hasOption("ibn")) {
        inlineBlankNodes = true;
    }

    // Check if the base URI should be set to be the same as the OWL ontology URI
    if (line.hasOption("ibu")) {
        inferBaseUri = true;
    }

    // Check if there are leading comments
    if (line.hasOption("lc")) {
        leadingComments = line.getOptionValues("lc");
    }

    // Check if there are trailing comments
    if (line.hasOption("tc")) {
        trailingComments = line.getOptionValues("tc");
    }

    // Check if there is a string data type option
    if (line.hasOption("sdt")) {
        stringDataTypeOption = SesameSortedRDFWriterFactory.StringDataTypeOptions
                .getByOptionValue(line.getOptionValue("sdt"));
    }

    // Check if an explicit indent string has been provided
    if (line.hasOption("i")) {
        indent = "ABC".replaceFirst("ABC", line.getOptionValue("i")); // use 'replaceFirst' to get cheap support for escaped characters like tabs
    }

    // Load RDF file.
    SesameSortedRDFWriterFactory.SourceFormats sourceFormat = null;
    if (line.hasOption("sfmt")) {
        sourceFormat = SesameSortedRDFWriterFactory.SourceFormats.getByOptionValue(line.getOptionValue("sfmt"));
    } else {
        sourceFormat = SesameSortedRDFWriterFactory.SourceFormats.auto;
    }
    if (sourceFormat == null) {
        logger.error("Unsupported or unrecognised source format: " + line.getOptionValue("sfmt"));
        return;
    }
    RDFFormat sesameSourceFormat = null;
    if (SesameSortedRDFWriterFactory.SourceFormats.auto.equals(sourceFormat)) {
        sesameSourceFormat = Rio.getParserFormatForFileName(sourceFilePath, RDFFormat.TURTLE);
    } else {
        sesameSourceFormat = sourceFormat.getRDFFormat();
    }
    if (sesameSourceFormat == null) {
        logger.error("Unsupported or unrecognised source format enum: " + sourceFormat);
    }
    Model sourceModel = Rio.parse(new FileInputStream(sourceFile), baseUriString, sesameSourceFormat);

    // Do any URI replacements
    if ((uriPattern != null) && (uriReplacement != null)) {
        Model replacedModel = new TreeModel();
        for (Statement st : sourceModel) {
            Resource replacedSubject = st.getSubject();
            if (replacedSubject instanceof URI) {
                replacedSubject = new URIImpl(
                        replacedSubject.stringValue().replaceFirst(uriPattern, uriReplacement));
            }

            URI replacedPredicate = st.getPredicate();
            replacedPredicate = new URIImpl(
                    replacedPredicate.stringValue().replaceFirst(uriPattern, uriReplacement));

            Value replacedObject = st.getObject();
            if (replacedObject instanceof URI) {
                replacedObject = new URIImpl(
                        replacedObject.stringValue().replaceFirst(uriPattern, uriReplacement));
            }

            Statement replacedStatement = new StatementImpl(replacedSubject, replacedPredicate, replacedObject);
            replacedModel.add(replacedStatement);
        }
        // Do URI replacements in namespaces as well.
        Set<Namespace> namespaces = sourceModel.getNamespaces();
        for (Namespace nmsp : namespaces) {
            replacedModel.setNamespace(nmsp.getPrefix(),
                    nmsp.getName().replaceFirst(uriPattern, uriReplacement));
        }
        sourceModel = replacedModel;
        // This is also the right time to do URI replacement in the base URI, if appropriate
        if (baseUri != null) {
            baseUriString = baseUriString.replaceFirst(uriPattern, uriReplacement);
            baseUri = new URIImpl(baseUriString);
        }
    }

    // Infer the base URI, if requested
    if (inferBaseUri) {
        LinkedList<URI> owlOntologyUris = new LinkedList<URI>();
        for (Statement st : sourceModel) {
            if ((SesameSortedRDFWriter.rdfType.equals(st.getPredicate()))
                    && (SesameSortedRDFWriter.owlOntology.equals(st.getObject()))
                    && (st.getSubject() instanceof URI)) {
                owlOntologyUris.add((URI) st.getSubject());
            }
        }
        if (owlOntologyUris.size() >= 1) {
            Comparator<URI> uriComparator = new Comparator<URI>() {
                @Override
                public int compare(URI uri1, URI uri2) {
                    return uri1.toString().compareTo(uri2.toString());
                }
            };
            owlOntologyUris.sort(uriComparator);
            inferredBaseUri = owlOntologyUris.getFirst();
        }
    }

    // Write sorted RDF file.
    SesameSortedRDFWriterFactory.TargetFormats targetFormat = null;
    if (line.hasOption("tfmt")) {
        targetFormat = SesameSortedRDFWriterFactory.TargetFormats.getByOptionValue(line.getOptionValue("tfmt"));
    } else {
        targetFormat = SesameSortedRDFWriterFactory.TargetFormats.turtle;
    }
    if (targetFormat == null) {
        logger.error("Unsupported or unrecognised target format: " + line.getOptionValue("tfmt"));
        return;
    }
    SesameSortedRDFWriter.ShortUriPreferences shortUriPref = null;
    if (line.hasOption("sup")) {
        shortUriPref = SesameSortedRDFWriter.ShortUriPreferences.getByOptionValue(line.getOptionValue("sup"));
    } else {
        shortUriPref = SesameSortedRDFWriter.ShortUriPreferences.prefix;
    }
    if (shortUriPref == null) {
        logger.error("Unsupported or unrecognised short URI preference: " + line.getOptionValue("sup"));
        return;
    }

    Writer targetWriter = new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8");
    SesameSortedRDFWriterFactory factory = new SesameSortedRDFWriterFactory(targetFormat);
    Map<String, Object> writerOptions = new HashMap<String, Object>();
    if (baseUri != null) {
        writerOptions.put("baseUri", baseUri);
    } else if (inferBaseUri && (inferredBaseUri != null)) {
        writerOptions.put("baseUri", inferredBaseUri);
    }
    if (indent != null) {
        writerOptions.put("indent", indent);
    }
    if (shortUriPref != null) {
        writerOptions.put("shortUriPref", shortUriPref);
    }
    writerOptions.put("useDtdSubset", useDtdSubset);
    writerOptions.put("inlineBlankNodes", inlineBlankNodes);
    writerOptions.put("leadingComments", leadingComments);
    writerOptions.put("trailingComments", trailingComments);
    writerOptions.put("stringDataTypeOption", stringDataTypeOption);
    RDFWriter rdfWriter = factory.getWriter(targetWriter, writerOptions);
    Rio.write(sourceModel, rdfWriter);
    targetWriter.flush();
    targetWriter.close();
}