Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

In this page you can find the example usage for java.util Comparator comparing.

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:com.netflix.spinnaker.halyard.cli.command.v1.NestableCommand.java

protected void showHelp() {
    AnsiStoryBuilder story = new AnsiStoryBuilder();
    int indentWidth = 2;

    AnsiParagraphBuilder paragraph = story.addParagraph();
    paragraph.addSnippet(getCommandName().toUpperCase()).addStyle(AnsiStyle.BOLD);
    story.addNewline();//from  w w  w. j av  a2  s .  co  m

    paragraph = story.addParagraph().setIndentWidth(indentWidth);
    String longDescription = getLongDescription() != null ? getLongDescription() : getDescription();
    paragraph.addSnippet(longDescription);
    story.addNewline();

    String usage = fullCommandName;

    if (!commander.getParameters().isEmpty()) {
        usage += " [parameters]";
    }

    if (!subcommands.isEmpty()) {
        usage += " [subcommands]";
    }

    paragraph = story.addParagraph();
    paragraph.addSnippet("USAGE").addStyle(AnsiStyle.BOLD);
    story.addNewline();

    paragraph = story.addParagraph().setIndentWidth(indentWidth);
    paragraph.addSnippet(usage);
    story.addNewline();

    List<ParameterDescription> parameters = commander.getParameters();
    parameters.sort(Comparator.comparing(ParameterDescription::getNames));

    int parameterCount = 0;

    if (!parameters.isEmpty()) {
        paragraph = story.addParagraph();
        paragraph.addSnippet("GLOBAL PARAMETERS").addStyle(AnsiStyle.BOLD);
        story.addNewline();

        for (ParameterDescription parameter : parameters) {
            if (GlobalOptions.isGlobalOption(parameter.getLongestName())) {
                formatParameter(story, parameter, indentWidth);
                parameterCount++;
            }
        }
    }

    if (parameters.size() > parameterCount) {
        paragraph = story.addParagraph();
        paragraph.addSnippet("PARAMETERS").addStyle(AnsiStyle.BOLD);
        story.addNewline();

        ParameterDescription mainParameter = commander.getMainParameter();
        if (mainParameter != null) {
            paragraph = story.addParagraph().setIndentWidth(indentWidth);
            paragraph.addSnippet(getMainParameter().toUpperCase()).addStyle(AnsiStyle.UNDERLINE);

            paragraph = story.addParagraph().setIndentWidth(indentWidth * 2);
            paragraph.addSnippet(mainParameter.getDescription());
            story.addNewline();
        }

        for (ParameterDescription parameter : parameters) {
            if (!GlobalOptions.isGlobalOption(parameter.getLongestName())) {
                formatParameter(story, parameter, indentWidth);
            }
        }
    }

    if (!subcommands.isEmpty()) {
        int maxLen = -1;
        for (String key : subcommands.keySet()) {
            if (key.length() > maxLen) {
                maxLen = key.length();
            }
        }

        paragraph = story.addParagraph();
        paragraph.addSnippet("SUBCOMMANDS").addStyle(AnsiStyle.BOLD);
        story.addNewline();

        List<String> keys = new ArrayList<>(subcommands.keySet());
        keys.sort(String::compareTo);

        for (String key : keys) {
            paragraph = story.addParagraph().setIndentWidth(indentWidth);
            paragraph.addSnippet(key).addStyle(AnsiStyle.BOLD);

            NestableCommand subcommand = subcommands.get(key);
            if (subcommand instanceof DeprecatedCommand) {
                paragraph.addSnippet(" ");
                paragraph.addSnippet("(Deprecated)").addStyle(AnsiStyle.UNDERLINE);
            }

            paragraph = story.addParagraph().setIndentWidth(indentWidth * 2);
            String shortDescription = subcommand.getShortDescription() != null
                    ? subcommand.getShortDescription()
                    : subcommand.getDescription();
            paragraph.addSnippet(shortDescription);
            story.addNewline();
        }
    }

    AnsiPrinter.out.println(story.toString());
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importSpeakerList() {
    this.speakerNameToSpeakerMap = new HashMap<>();
    this.talkUrlSet = new HashSet<>();
    List<Speaker> speakerList = new ArrayList<>();

    String speakersUrl = conferenceBaseUrl + "/speakers";
    LOGGER.debug("Sending a request to: " + speakersUrl);
    JsonArray speakerArray = readJson(speakersUrl, JsonReader::readArray);

    for (int i = 0; i < speakerArray.size(); i++) {
        String speakerUrl = speakerArray.getJsonObject(i).getJsonArray("links").getJsonObject(0)
                .getString("href");
        LOGGER.debug("Sending a request to: " + speakerUrl);
        JsonObject speakerObject = readJson(speakerUrl, JsonReader::readObject);

        String speakerId = speakerObject.getString("uuid");
        String speakerName = speakerObject.getString("firstName") + " " + speakerObject.getString("lastName");

        if (Arrays.asList(IGNORED_SPEAKER_NAMES).contains(speakerName)) {
            continue;
        }//w ww .j  a v  a  2  s . c om
        Speaker speaker = new Speaker((long) i);
        speaker.setName(speakerName);
        speaker.withPreferredRoomTagSet(new HashSet<>()).withPreferredTimeslotTagSet(new HashSet<>())
                .withProhibitedRoomTagSet(new HashSet<>()).withProhibitedTimeslotTagSet(new HashSet<>())
                .withRequiredRoomTagSet(new HashSet<>()).withRequiredTimeslotTagSet(new HashSet<>())
                .withUnavailableTimeslotSet(new HashSet<>()).withUndesiredRoomTagSet(new HashSet<>())
                .withUndesiredTimeslotTagSet(new HashSet<>());
        speakerList.add(speaker);
        if (speakerNameToSpeakerMap.keySet().contains(speakerName)) {
            throw new IllegalStateException("Speaker (" + speakerName + ") with id (" + speakerId
                    + ") already exists in the speaker list");
        }
        speakerNameToSpeakerMap.put(speakerName, speaker);

        JsonArray speakerTalksArray = speakerObject.getJsonArray("acceptedTalks");
        for (int j = 0; j < speakerTalksArray.size(); j++) {
            String talkUrl = speakerTalksArray.getJsonObject(j).getJsonArray("links").getJsonObject(0)
                    .getString("href");
            talkUrlSet.add(talkUrl);
        }
    }

    speakerList.sort(Comparator.comparing(Speaker::getName));
    solution.setSpeakerList(speakerList);
}

From source file:com.marand.thinkmed.medications.dto.report.TherapyDayReportUtils.java

public static String getTherapyApplicationColumnValue(List<AdministrationDto> therapyAdministrations,
        @Nonnull final TherapyDto order, @Nonnull final Date startDate, final int column,
        @Nonnull Locale locale) {
    final DateTime day = new DateTime(startDate).plusDays(column).withTimeAtStartOfDay();
    final StringBuilder administrationString = new StringBuilder();

    if (therapyAdministrations != null) {
        Collections.sort(therapyAdministrations,
                Comparator.comparing(AdministrationDto::getAdministrationTime));
        for (final AdministrationDto administration : therapyAdministrations) {
            final DateTime administrationTime = administration.getAdministrationTime();
            if (administrationTime != null && administrationTime.withTimeAtStartOfDay().isEqual(day)) {
                final StringBuilder dose = new StringBuilder();

                if (administration.getAdministrationResult() == AdministrationResultEnum.DEFER) {
                    dose.append(StringUtils.capitalize(getDictionaryEntry("administration.defer", locale)));

                    if (administration.getNotAdministeredReason() != null
                            && administration.getNotAdministeredReason().getName() != null) {
                        dose.append(" - ").append(administration.getNotAdministeredReason().getName());
                    }/*from w w w  . j av  a 2 s.c  o  m*/
                } else if (administration.getAdministrationResult() == AdministrationResultEnum.NOT_GIVEN) {
                    dose.append(StringUtils.capitalize(getDictionaryEntry("administration.not.given", locale)));

                    if (administration.getNotAdministeredReason() != null
                            && administration.getNotAdministeredReason().getName() != null) {
                        dose.append(" - ").append(administration.getNotAdministeredReason().getName());
                    }
                } else {
                    if (administration instanceof StartAdministrationDto) {
                        final TherapyDoseDto administeredDose = ((StartAdministrationDto) administration)
                                .getAdministeredDose();
                        if (administeredDose != null && administeredDose.getNumerator() != null
                                && administeredDose.getNumeratorUnit() != null) {
                            try {
                                dose.append(NumberFormatters.doubleFormatter2(locale)
                                        .valueToString(administeredDose.getNumerator()) + " "
                                        + administeredDose.getNumeratorUnit());
                            } catch (final ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    } else if (administration instanceof AdjustInfusionAdministrationDto) {
                        final TherapyDoseDto administeredDose = ((AdjustInfusionAdministrationDto) administration)
                                .getAdministeredDose();
                        if (administeredDose.getNumerator() != null
                                && administeredDose.getNumeratorUnit() != null) {
                            try {
                                dose.append(NumberFormatters.doubleFormatter2(locale)
                                        .valueToString(administeredDose.getNumerator()) + " "
                                        + administeredDose.getNumeratorUnit());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    } else if (administration instanceof InfusionSetChangeDto) {
                        //noinspection SwitchStatement
                        switch (((InfusionSetChangeDto) administration).getInfusionSetChangeEnum()) {
                        case INFUSION_SYRINGE_CHANGE:
                            dose.append(getDictionaryEntry("infusion.syringe.change", locale));
                            break;

                        case INFUSION_SYSTEM_CHANGE:
                            dose.append(getDictionaryEntry("infusion.system.change", locale));
                            break;
                        }
                    } else if (administration instanceof StopAdministrationDto) {
                        dose.append(getDictionaryEntry("infusion.stopped", locale));
                    }
                }

                if (administration.getComment() != null) {
                    dose.append(" - ").append(administration.getComment());
                }

                administrationString.append(String.format("<b>%02d:%02d<br></b>%s<br><br>",
                        administrationTime.getHourOfDay(), administrationTime.getMinuteOfHour(), dose));
            }
        }
    }

    return administrationString.toString();
}

From source file:org.finra.herd.swaggergen.RestControllerProcessor.java

/**
 * Processes a Spring MVC REST controller class that is annotated with RestController. Also collects any required model objects based on parameters and
 * return types of each endpoint into the specified model classes set.
 *
 * @param clazz the class to process//from w  w w.  j  ava  2  s  .c om
 *
 * @throws MojoExecutionException if any errors were encountered.
 */
private void processRestControllerClass(Class<?> clazz) throws MojoExecutionException {
    // Get the Java class source information.
    JavaClassSource javaClassSource = sourceMap.get(clazz.getSimpleName());
    if (javaClassSource == null) {
        throw new MojoExecutionException("No source resource found for class \"" + clazz.getName() + "\".");
    }

    Api api = clazz.getAnnotation(Api.class);
    boolean hidden = api != null && api.hidden();

    if ((clazz.getAnnotation(RestController.class) != null) && (!hidden)) {
        log.debug("Processing RestController class \"" + clazz.getName() + "\".");

        // Default the tag name to the simple class name.
        String tagName = clazz.getSimpleName();

        // See if the "Api" annotation exists.
        if (api != null && api.tags().length > 0) {
            // The "Api" annotation was found so use it's configured tag.
            tagName = api.tags()[0];
        } else {
            // No "Api" annotation so try to get the tag name from the class name. If not, we will stick with the default simple class name.
            Matcher matcher = tagPattern.matcher(clazz.getSimpleName());
            if (matcher.find()) {
                // If our class has the form
                tagName = matcher.group("tag");
            }
        }
        log.debug("Using tag name \"" + tagName + "\".");

        // Add the tag and process each method.
        swagger.addTag(new Tag().name(tagName));

        List<Method> methods = Lists.newArrayList(clazz.getDeclaredMethods());
        // Based on the Java 8 doc, getDeclaredMethods() is not guaranteed sorted
        // In order to be sure we generate stable API when the URL's don't change
        // we can give it a sort order based on the first URI hit in the request mapping
        List<Method> outMethods = methods.stream().filter((method) -> {
            RequestMapping rm = method.getAnnotation(RequestMapping.class);
            ApiOperation apiOp = method.getAnnotation(ApiOperation.class);
            return rm != null && // Has RequestMapping
            rm.value().length > 0 && // has at least 1 URI
            rm.method().length > 0 && // has at least 1 HttpMethod
            (apiOp == null || !apiOp.hidden()); // marked as a hidden ApiOperation
        }).sorted(Comparator.comparing(a -> ((Method) a).getAnnotation(RequestMapping.class).value()[0])
                .thenComparing(a -> ((Method) a).getAnnotation(RequestMapping.class).method()[0]))
                .collect(Collectors.toList());

        for (Method method : outMethods) {
            // Get the method source information.
            List<Class<?>> methodParamClasses = new ArrayList<>();
            for (Parameter parameter : method.getParameters()) {
                methodParamClasses.add(parameter.getType());
            }
            MethodSource<JavaClassSource> methodSource = javaClassSource.getMethod(method.getName(),
                    methodParamClasses.toArray(new Class<?>[methodParamClasses.size()]));
            if (methodSource == null) {
                throw new MojoExecutionException("No method source found for class \"" + clazz.getName()
                        + "\" and method name \"" + method.getName() + "\".");
            }

            // Process the REST controller method along with its source information.
            processRestControllerMethod(method, clazz.getAnnotation(RequestMapping.class), tagName,
                    methodSource);
        }
    } else {
        log.debug("Skipping class \"" + clazz.getName()
                + "\" because it is either not a RestController or it is hidden.");
    }
}

From source file:org.apache.hyracks.control.common.config.ConfigManager.java

@SuppressWarnings({ "squid:S106", "squid:S1147" }) // use of System.err, System.exit()
private List<String> processCommandLine(Collection<Section> sections, OptionHandlerFilter usageFilter,
        BiConsumer<IOption, Object> setAction) throws CmdLineException {
    final Args4jBean bean = new Args4jBean();
    CmdLineParser cmdLineParser = new CmdLineParser(bean);
    final List<String> appArgs = new ArrayList<>();
    List<IOption> commandLineOptions = new ArrayList<>();
    for (Map.Entry<Section, Map<String, IOption>> sectionMapEntry : sectionMap.entrySet()) {
        if (!sections.contains(sectionMapEntry.getKey())) {
            continue;
        }//from  ww w  .  j av  a  2s.c  o m
        for (IOption option : sectionMapEntry.getValue().values()) {
            if (option.section() != Section.VIRTUAL) {
                commandLineOptions.add(option);
            }
        }
    }
    commandLineOptions.sort(Comparator.comparing(IOption::cmdline));

    commandLineOptions.forEach(option -> cmdLineParser.addOption(new Args4jSetter(option, setAction, false),
            new Args4jOption(option, this, option.type().targetType())));

    if (!argListeners.isEmpty()) {
        cmdLineParser.addArgument(new Args4jSetter(o -> appArgs.add(String.valueOf(o)), true, String.class),
                new Args4jArgument());
    }
    LOGGER.fine("parsing cmdline: " + Arrays.toString(args));
    if (args == null || args.length == 0) {
        LOGGER.info("no command line args supplied");
        return appArgs;
    }
    try {
        cmdLineParser.parseArgument(args);
    } catch (CmdLineException e) {
        if (!bean.help) {
            ConfigUtils.printUsage(e, usageFilter, System.err);
            throw e;
        } else {
            LOGGER.log(Level.FINE, "Ignoring parse exception due to -help", e);
        }
    }
    if (bean.help) {
        ConfigUtils.printUsage(cmdLineParser, usageFilter, System.err);
        System.exit(0);
    } else if (bean.version) {
        System.err.println(versionString);
        System.exit(0);
    }
    return appArgs;
}

From source file:com.mycompany.capstone.controllers.BlogPostController.java

@RequestMapping(value = "/all", method = RequestMethod.GET)
public String showAllBlogs(Map model) {

    List<AdminPage> adminPage = adminPageDao.listAdminPages();
    List<Comment> comments = new ArrayList();

    List<BlogPost> blogPosts = blogPostDao.listActivePosts();
    List<User> authors = userDao.listUsers();
    for (BlogPost b : blogPosts) {
        for (User u : authors) {
            if (b.getAuthor().getId() == u.getId()) {
                b.setAuthorName(u.getFirstName() + " " + u.getLastName());
            }/*from  w w  w. j ava  2 s.  c om*/
        }
    }

    BlogPost blogPost = blogPosts.stream().max(Comparator.comparing(a -> a.getCreationDate())).get();

    List<Comment> commentList = commentDao.listComments();
    for (Comment c : commentList) {
        if (c.getBlogPostId() == blogPost.getId()) {
            comments.add(c);
        }
    }

    model.put("blogPost", blogPost);
    model.put("blogPosts", blogPosts);
    model.put("adminPage", adminPage);

    model.put("comments", comments);
    model.put("adminPage", adminPage);
    return "all_blogs";
}

From source file:alfio.controller.api.support.TicketHelper.java

private static List<Pair<String, String>> mapISOCountries(Stream<String> isoCountries, Locale locale) {
    return isoCountries.map(isoCode -> Pair.of(isoCode, new Locale("", isoCode).getDisplayCountry(locale)))
            .sorted(Comparator.comparing(Pair::getRight)).collect(Collectors.toList());
}

From source file:com.denkbares.semanticcore.utils.ResultTableModel.java

public static ResultTableModel fromCSV(String csv) throws IOException {
    try (CSVParser parser = CSVFormat.DEFAULT.withHeader().parse(new StringReader(csv))) {

        // read the header
        Map<String, Integer> headerMap = parser.getHeaderMap();
        List<String> variables = headerMap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue))
                .map(Map.Entry::getKey).collect(Collectors.toList());

        // read the rows
        List<TableRow> rows = new LinkedList<>();
        for (final CSVRecord record : parser) {
            SimpleTableRow row = new SimpleTableRow();
            for (String variable : variables) {
                String value = record.get(variable);
                if (value != null) {
                    row.addValue(variable, new LiteralImpl(value));
                }// w  w  w .ja  v a 2 s.c  o m
            }
            rows.add(row);
        }

        //  and return the parsed table
        return new ResultTableModel(rows, variables);
    }
}

From source file:org.apache.sysml.hops.rewrite.HopRewriteUtils.java

public static Hop getLargestInput(Hop hop) {
    return hop.getInput().stream().max(Comparator.comparing(h -> h.getLength())).orElse(null);
}

From source file:org.apache.sysml.hops.codegen.opt.ReachabilityGraph.java

private InterestingPoint[] sortBySize(InterestingPoint[] points, CPlanMemoTable memo, boolean asc) {
    return Arrays.stream(points)
            .sorted(Comparator.comparing(p -> (asc ? 1 : -1) * getSize(memo.getHopRefs().get(p.getToHopID()))))
            .toArray(InterestingPoint[]::new);
}