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> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor,
        Comparator<? super U> keyComparator) 

Source Link

Document

Accepts a function that extracts a sort key from a type T , and returns a Comparator that compares by that sort key using the specified Comparator .

Usage

From source file:main.java.RMDupper.java

/**
 * This Method reads a SAM File and parses the input
 * Currently, only merged Reads with the "M" Flag in front are checked for Duplicates.
 * R/F Flags are simply written into output File, also other "non-flagged" ones.
 *///from  w  w  w  .ja  v a2s  .  co  m
public void readSAMFile() {
    Comparator<SAMRecord> samRecordComparatorForRecordBuffer = new SAMRecordPositionAndQualityComparator();
    Comparator<SAMRecord> samRecordComparatorForDuplicateBuffer;

    if (this.allReadsAsMerged) {
        samRecordComparatorForDuplicateBuffer = new SAMRecordQualityComparator();
    } else {
        samRecordComparatorForDuplicateBuffer = new SAMRecordQualityComparatorPreferMerged();
    }

    PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>> recordBuffer = new PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>>(
            1000, Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getRight,
                    samRecordComparatorForRecordBuffer));
    PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>> duplicateBuffer = new PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>>(
            1000, Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getRight,
                    samRecordComparatorForDuplicateBuffer.reversed()));
    Set<String> discardSet = new HashSet<String>(1000);
    String referenceName = SAMRecord.NO_ALIGNMENT_REFERENCE_NAME;

    Iterator it = inputSam.iterator();
    while (it.hasNext()) {
        SAMRecord curr = (SAMRecord) it.next();
        if (curr.getReferenceName() == SAMRecord.NO_ALIGNMENT_REFERENCE_NAME) {
            this.outputSam.addAlignment(curr);
        } else {
            if (referenceName == curr.getReferenceName()) {
                queueOrOutput(this.dupStats, this.oc, this.outputSam, this.allReadsAsMerged, recordBuffer,
                        duplicateBuffer, discardSet, curr);
            } else {
                flushQueue(this.dupStats, this.oc, this.outputSam, this.allReadsAsMerged, recordBuffer,
                        duplicateBuffer, discardSet);
                queueOrOutput(this.dupStats, this.oc, this.outputSam, this.allReadsAsMerged, recordBuffer,
                        duplicateBuffer, discardSet, curr);
                referenceName = curr.getReferenceName();
            }
        }

        this.dupStats.total++;
        if (this.dupStats.total % 100000 == 0) {
            if (!piped) {
                System.err.println("Reads treated: " + this.dupStats.total);
            }
        }
    }
    flushQueue(this.dupStats, this.oc, this.outputSam, this.allReadsAsMerged, recordBuffer, duplicateBuffer,
            discardSet);
}

From source file:org.eclipse.sw360.datahandler.common.CommonUtils.java

public static Optional<Attachment> getBestClearingReport(Release release) {
    return nullToEmptyCollection(release.getAttachments()).stream()
            .filter(att -> att.getAttachmentType() == AttachmentType.CLEARING_REPORT)
            .max(Comparator.comparing(Attachment::getCheckStatus, CHECK_STATUS_COMPARATOR));
}

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);
    }//  w  ww  .j a  v  a  2  s.c o m
    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.kitodo.production.services.data.ProcessService.java

/**
 * Filter and sort after creation date list of process properties for
 * correction and solution messages.//from ww w .  j  a v a2 s  .com
 *
 * @return list of ProcessProperty objects
 */
public List<PropertyDTO> getSortedCorrectionSolutionMessages(ProcessDTO process) {
    List<PropertyDTO> filteredList = filterForCorrectionSolutionMessages(process.getProperties());

    if (filteredList.size() > 1) {
        filteredList.sort(Comparator.comparing(PropertyDTO::getCreationDate,
                Comparator.nullsFirst(Comparator.naturalOrder())));
    }

    return filteredList;
}

From source file:sg.ncl.MainController.java

@RequestMapping("/admin/usage")
public String adminTeamUsage(Model model, @RequestParam(value = "start", required = false) String start,
        @RequestParam(value = "end", required = false) String end,
        @RequestParam(value = "organizationType", required = false) String organizationType,
        @RequestParam(value = "team", required = false) String team,
        final RedirectAttributes redirectAttributes, HttpSession session)
        throws IOException, WebServiceRuntimeException {
    if (!validateIfAdmin(session)) {
        return NO_PERMISSION_PAGE;
    }/*from w  w w .j  a va  2s  .c  o  m*/

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    ZonedDateTime nowDate = ZonedDateTime.now();
    String now = nowDate.format(formatter);
    if (start == null) {
        start = nowDate.with(firstDayOfMonth()).format(formatter);
    }
    if (end == null) {
        end = now;
    }
    if (now.compareTo(start) < 0 || now.compareTo(end) < 0) {
        redirectAttributes.addFlashAttribute(MESSAGE, "Period selected is beyond current date (today).");
        return REDIRECT_TEAM_USAGE;
    }

    // get list of teamids
    HttpEntity<String> request = createHttpEntityHeaderOnly();
    ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request,
            String.class);
    JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString());

    List<Team2> searchTeams = new ArrayList<>();
    TeamManager2 teamManager2 = new TeamManager2();
    getSearchTeams(organizationType, team, jsonArray, searchTeams, teamManager2);

    if (!searchTeams.isEmpty()) {
        List<String> dates = getDates(start, end, formatter);

        Map<String, List<Long>> teamUsages = new HashMap<>();
        Long totalUsage = 0L;
        for (Team2 team2 : searchTeams) {
            try {
                List<Long> usages = new ArrayList<>();
                totalUsage += getTeamUsageStatistics(team2, start, end, request, usages);
                teamUsages.put(team2.getName(), usages);
            } catch (RestClientException rce) {
                log.warn("Error connecting to sio analytics service for team usage: {}", rce);
                redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
                return REDIRECT_TEAM_USAGE;
            } catch (StartDateAfterEndDateException sde) {
                redirectAttributes.addFlashAttribute(MESSAGE, ERR_START_DATE_AFTER_END_DATE);
                return REDIRECT_TEAM_USAGE;
            }
        }
        model.addAttribute("dates", dates);
        model.addAttribute("teamUsages", teamUsages);
        model.addAttribute("totalUsage", totalUsage);
    }

    List<Team2> allTeams = new ArrayList<>(teamManager2.getTeamMap().values());
    allTeams.sort(Comparator.comparing(Team2::getName, String.CASE_INSENSITIVE_ORDER));
    model.addAttribute(ALL_TEAMS, allTeams);
    model.addAttribute("start", start);
    model.addAttribute("end", end);
    model.addAttribute("organizationType", organizationType);
    model.addAttribute("team", team);
    return "usage_statistics";
}

From source file:sg.ncl.MainController.java

/**
 * Allows admins to:/*from w ww  .  ja  va 2s.c  o  m*/
 * view reservations
 * reserve nodes
 * release nodes
 */
@GetMapping("/admin/nodesReservation")
public String adminNodesReservation(
        @ModelAttribute("reservationStatusForm") ReservationStatusForm reservationStatusForm, Model model,
        HttpSession session) {
    if (!validateIfAdmin(session)) {
        return NO_PERMISSION_PAGE;
    }

    List<Team2> allTeams = new ArrayList<>(getTeamMap().values());
    allTeams.sort(Comparator.comparing(Team2::getName, String.CASE_INSENSITIVE_ORDER));
    model.addAttribute(ALL_TEAMS, allTeams);
    model.addAttribute(RESERVATION_STATUS_FORM, reservationStatusForm);

    return "node_reservation";
}

From source file:sg.ncl.MainController.java

@PostMapping("/admin/nodesReservation")
public String adminNodesReservation(
        @ModelAttribute("reservationStatusForm") ReservationStatusForm reservationStatusForm,
        BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) {
    List<Team2> allTeams = new ArrayList<>(getTeamMap().values());
    allTeams.sort(Comparator.comparing(Team2::getName, String.CASE_INSENSITIVE_ORDER));
    model.addAttribute(ALL_TEAMS, allTeams);

    // sanitization
    if (bindingResult.hasErrors()) {
        model.addAttribute(ALL_TEAMS, allTeams);
        model.addAttribute(RESERVATION_STATUS_FORM, reservationStatusForm);
        model.addAttribute(STATUS, NODES_RESERVATION_FAIL);
        model.addAttribute(MESSAGE, "form errors");
        return "node_reservation";
    }/*from  w w w.  j a  v a 2s. c  o  m*/

    switch (reservationStatusForm.getAction()) {
    case "release":
        releaseNodes(reservationStatusForm, redirectAttributes);
        break;
    case "reserve":
        reserveNodes(reservationStatusForm, redirectAttributes);
        break;
    case "check":
        checkReservation(reservationStatusForm, redirectAttributes);
        break;
    default:
        // error
        redirectAttributes.addFlashAttribute(STATUS, NODES_RESERVATION_FAIL);
        redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD);
        break;
    }

    redirectAttributes.addFlashAttribute(RESERVATION_STATUS_FORM, reservationStatusForm);
    redirectAttributes.addFlashAttribute(ALL_TEAMS, allTeams);

    return "redirect:/admin/nodesReservation";
}