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:org.phoenicis.repository.types.LocalRepository.java

private List<TypeDTO> fetchTypes(File[] typeDirectories) {
    final List<TypeDTO> results = new ArrayList<>();

    for (File typeDirectory : typeDirectories) {
        if (typeDirectory.isDirectory() && !typeDirectory.getName().startsWith(".")) {
            final File typeJson = new File(typeDirectory, "type.json");

            if (typeJson.exists()) {
                final TypeDTO jsonTypeDTO = unSerializeType(typeJson);
                final TypeDTO.Builder typeDTOBuilder = new TypeDTO.Builder(jsonTypeDTO);

                if (StringUtils.isBlank(jsonTypeDTO.getId())) {
                    if (!StringUtils.isBlank(jsonTypeDTO.getName())) {
                        typeDTOBuilder.withId(jsonTypeDTO.getName().replaceAll(ID_REGEX, ""));
                    } else {
                        typeDTOBuilder.withId(typeDirectory.getName().replaceAll(ID_REGEX, ""));
                    }/*from  w  w w .j  a v  a  2  s  . co m*/
                }

                final File typeIconFile = new File(typeDirectory, ICON_NAME);
                if (typeIconFile.exists()) {
                    typeDTOBuilder.withIcon(typeIconFile.toURI());
                }

                typeDTOBuilder.withCategories(fetchCategories(typeDTOBuilder.getId(), typeDirectory));

                final TypeDTO type = typeDTOBuilder.build();
                results.add(type);
            }
        }
    }

    results.sort(Comparator.comparing(TypeDTO::getName));
    return results;
}

From source file:net.minecraftforge.fml.common.network.internal.FMLNetworkHandler.java

/**
 * @param listData map of modId string to version string, represents the mods available on the given side
 * @param side the side that listData is coming from, either client or server
 * @return null if everything is fine, returns a string error message if there are mod rejections
 *///from ww w  . j  a va2  s  .  c om
@Nullable
public static String checkModList(Map<String, String> listData, Side side) {
    List<Pair<ModContainer, String>> rejects = NetworkRegistry.INSTANCE.registry().entrySet().stream()
            .map(entry -> Pair.of(entry.getKey(), entry.getValue().checkCompatible(listData, side)))
            .filter(pair -> pair.getValue() != null).sorted(Comparator.comparing(o -> o.getKey().getName()))
            .collect(Collectors.toList());
    if (rejects.isEmpty()) {
        return null;
    } else {
        List<String> rejectStrings = new ArrayList<>();
        for (Pair<ModContainer, String> reject : rejects) {
            ModContainer modContainer = reject.getKey();
            rejectStrings.add(modContainer.getName() + ": " + reject.getValue());
        }
        String rejectString = String.join("\n", rejectStrings);
        FMLLog.log.info("Rejecting connection {}: {}", side, rejectString);
        return String.format("Server Mod rejections:\n%s", rejectString);
    }
}

From source file:org.silverpeas.core.webapi.calendar.CalendarEventRecurrenceEntity.java

protected CalendarEventRecurrenceEntity decorate(final CalendarEvent event, final ZoneId zoneId) {
    final Recurrence recurrence = event.getRecurrence();
    frequency = FrequencyEntity.from(recurrence.getFrequency());
    count = recurrence.getRecurrenceCount();
    Optional<Temporal> optionalDateTime = recurrence.getRecurrenceEndDate();
    endDate = null;//from w w  w . j a va 2  s.  c o m
    optionalDateTime.ifPresent(t -> endDate = TemporalConverter.applyByType(t, LocalDate::toString,
            dateTime -> formatDateWithOffset(event.asCalendarComponent(), dateTime, zoneId)));
    daysOfWeek = recurrence.getDaysOfWeek().stream()
            .sorted(Comparator.comparing(DayOfWeekOccurrence::dayOfWeek)).map(DayOfWeekOccurrenceEntity::from)
            .collect(Collectors.toList());
    return this;
}

From source file:org.obiba.mica.micaConfig.service.OpalService.java

public List<Taxonomy> getTaxonomies() {
    Map<String, Taxonomy> taxonomies = getTaxonomiesInternal();
    List<Taxonomy> taxonomyList = Lists.newArrayList(taxonomies.values());
    Collections.sort(taxonomyList, Comparator.comparing(TaxonomyEntity::getName));
    return taxonomyList;
}

From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java

public AWS4SignatureBuilder canonicalQueryString(final String canonicalQueryString) {
    final String defaultString = StringUtils.defaultString(canonicalQueryString);

    // this way of parsing the query string is the only way to satisfy the
    // test-suite, therefore we do it with a matcher:
    final Matcher matcher = QUERY_STRING_MATCHING_PATTERN.matcher(defaultString);
    final List<KeyValue<String, String>> parameters = Lists.newLinkedList();

    while (matcher.find()) {
        final String key = StringUtils.trim(matcher.group(1));
        final String value = StringUtils.trim(matcher.group(2));
        parameters.add(new DefaultKeyValue<>(key, value));
    }/*from w w w .ja  v  a2s  .c  o  m*/

    this.canonicalQueryString = parameters.stream().sorted(Comparator.comparing(KeyValue::getKey))
            .map(kv -> queryParameterEscape(kv.getKey()) + "=" + queryParameterEscape(kv.getValue()))
            .collect(Collectors.joining("&"));

    return this;
}

From source file:org.fenixedu.qubdocs.ui.documenttemplates.AcademicServiceRequestTemplateController.java

@RequestMapping(value = _SEARCHTEMPLATES_URI)
public String searchTemplates(@RequestParam(value = "active", required = false) java.lang.Boolean active,
        @RequestParam(value = "name", required = false) org.fenixedu.commons.i18n.LocalizedString name,
        @RequestParam(value = "servicerequesttype", required = false) org.fenixedu.academic.domain.serviceRequests.ServiceRequestType serviceRequestType,
        @RequestParam(value = "custom", required = false) java.lang.Boolean custom, Model model) {
    List<AcademicServiceRequestTemplate> searchtemplatesResultsDataSet = filterSearchTemplates(active, name,
            serviceRequestType, custom);

    model.addAttribute("searchtemplatesResultsDataSet", searchtemplatesResultsDataSet);
    model.addAttribute("AcademicServiceRequestTemplate_serviceRequestType_options",
            org.fenixedu.academic.domain.serviceRequests.ServiceRequestType.findActive()
                    .sorted(Comparator.comparing(ServiceRequestType::getName)).collect(Collectors.toList()));
    return "qubdocsreports/documenttemplates/academicservicerequesttemplate/searchtemplates";
}

From source file:alfio.controller.api.admin.EventApiController.java

@RequestMapping(value = "/events", method = GET, headers = "Authorization")
public List<EventListItem> getAllEventsForExternal(Principal principal, HttpServletRequest request) {
    List<Integer> userOrganizations = userManager.findUserOrganizations(principal.getName()).stream()
            .map(Organization::getId).collect(toList());
    return eventManager.getActiveEvents().stream()
            .filter(e -> userOrganizations.contains(e.getOrganizationId()))
            .sorted(Comparator.comparing(e -> e.getBegin().withZoneSameInstant(ZoneId.systemDefault())))
            .map(s -> new EventListItem(s, request.getContextPath(), descriptionsLoader.eventDescriptions()))
            .collect(toList());/*  w w w  .j  av  a2 s .  c  om*/
}

From source file:ddf.catalog.transformer.OverlayMetacardTransformer.java

public static List<Vector> calculateBoundingBox(List<Vector> boundary) {
    double maxLon = Collections.max(boundary, Comparator.comparing(v -> v.get(0))).get(0);
    double minLon = Collections.min(boundary, Comparator.comparing(v -> v.get(0))).get(0);
    double maxLat = Collections.max(boundary, Comparator.comparing(v -> v.get(1))).get(1);
    double minLat = Collections.min(boundary, Comparator.comparing(v -> v.get(1))).get(1);

    List<Vector> boundingBox = new ArrayList<>();
    boundingBox.add(new BasicVector(new double[] { minLon, maxLat }));
    boundingBox.add(new BasicVector(new double[] { maxLon, minLat }));

    return boundingBox;
}

From source file:pt.ist.applications.admissions.ui.ApplicationsAdmissionsController.java

@RequestMapping(value = "/contest/{contest}", method = RequestMethod.GET)
public String contest(@PathVariable Contest contest, @RequestParam(required = false) String hash,
        final Model model, final HttpServletRequest request) {
    if (Authenticate.getUser() == null) {
        I18N.setLocale(request.getSession(false), new Locale("en", "GB"));
    }//from  w w w  .j av a2s . c o  m

    final JsonObject result = toJsonObject(contest);
    if (Contest.canManageContests() || contest.verifyHashForView(hash)) {
        final JsonArray candidates = contest.getCandidateSet().stream()
                .sorted(Comparator.comparing((Candidate c) -> c.getCandidateNumber())).map(this::toJsonObject)
                .collect(Utils.toJsonArray());
        result.add("candidates", candidates);
    }
    model.addAttribute("contest", result);
    return "applications-admissions/contest";
}

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.");
    }//w ww.  j a va2 s.com

    //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);
}