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:View.Visualize.java

public void getBarChartData(Integer nameColumn, Integer valueColumn, Table table, BarChart barChart,
        Boolean newSeries, Boolean rowCounter) {
    data.clear();/*from w  w w  . j a  v  a  2 s.c o  m*/
    ObservableList<XYChart.Data> barChartData = FXCollections.observableArrayList();
    XYChart.Series series1 = new XYChart.Series();

    if (!newSeries) {
        series1.getData().clear();
        barChart.getData().clear();

    }
    barChart.setAnimated(false);//bug fix
    addDataFromTable(table, nameColumn, valueColumn, rowCounter);

    data.entrySet().stream().map(entry -> new XYChart.Data(entry.getKey(), entry.getValue()))
            .forEach(barChartData::add);

    barChart.getData().addAll(series1);
    series1.getData().addAll(barChartData);

    series1.getData().sort(Comparator.comparing(BarChart.Data<String, Double>::getYValue).reversed());

    setupHover(series1);
    addColorChangeOnIndividual(barChartData);

}

From source file:com.github.aptd.simulation.elements.graph.network.local.CPlatform.java

@Override
protected boolean updatestate() {
    if (m_input.isEmpty())
        return false;

    final List<IMessage> l_arrivingtrains = m_input.get(EMessageType.TRAIN_TO_PLATFORM_ARRIVING);
    final List<IMessage> l_departingtrains = m_input.get(EMessageType.TRAIN_TO_PLATFORM_DEPARTING);
    final List<IMessage> l_subscribingpassengers = m_input.get(EMessageType.PASSENGER_TO_PLATFORM_SUBSCRIBE);
    final List<IMessage> l_unsubscribingpassengers = m_input
            .get(EMessageType.PASSENGER_TO_PLATFORM_UNSUBSCRIBE);

    if (l_departingtrains.size() > 1)
        throw new RuntimeException(
                m_id + " has multiple trains departing simultaneously at " + m_time.current());
    if (l_departingtrains.size() == 1) {
        if (m_train != l_departingtrains.get(0).sender())
            throw new RuntimeException(m_id + " has a train departing that's not there at " + m_time.current());
        m_passengers.stream().forEach(p -> output(
                new CMessage(this, p.id(), EMessageType.PLATFORM_TO_PASSENGER_TRAINDEPARTED, m_train.id())));
        m_train = null;/*w  ww  . jav a2  s  .  co m*/
        m_doors.clear();
    }

    l_subscribingpassengers.stream().forEach(msg -> {
        m_passengers.add((IPassenger) msg.sender());
        if (m_train != null)
            output(new CMessage(this, msg.sender().id(), EMessageType.PLATFORM_TO_PASSENGER_TRAINARRIVED,
                    m_train.id(), m_doors.toArray()));
    });
    l_unsubscribingpassengers.stream().forEach(msg -> m_passengers.remove(msg.sender()));

    if (l_arrivingtrains.size() > 1)
        throw new RuntimeException(
                m_id + " has multiple trains arriving simultaneously at " + m_time.current());
    if (l_arrivingtrains.size() == 1) {
        if (m_train != null)
            throw new RuntimeException(
                    m_id + " has a second train arriving without the first departing at " + m_time.current());
        m_train = (ITrain) l_arrivingtrains.get(0).sender();
        Arrays.stream(l_arrivingtrains.get(0).content()).map(o -> (IDoor<?>) o)
                .sorted(Comparator.comparing(IDoor::id)).forEachOrdered(m_doors::add);
        m_passengers.stream().forEach(p -> output(new CMessage(this, p.id(),
                EMessageType.PLATFORM_TO_PASSENGER_TRAINARRIVED, m_train.id(), m_doors.toArray())));
    }
    return true;
}

From source file:org.ajoberstar.reckon.core.git.GitInventorySupplier.java

private TaggedVersion findBase(RevWalk walk, RevCommit head, Stream<TaggedVersion> versions)
        throws IOException {
    walk.reset();/*from www  . java 2s. c o m*/
    walk.setRevFilter(RevFilter.ALL);
    walk.markStart(head);

    Map<RevCommit, List<TaggedVersion>> versionsByCommit = versions
            .collect(Collectors.groupingBy(TaggedVersion::getCommit));

    Stream.Builder<List<TaggedVersion>> builder = Stream.builder();

    for (RevCommit commit : walk) {
        List<TaggedVersion> matches = versionsByCommit.get(commit);
        if (matches != null) {
            // Parents can't be "nearer". Exclude them to avoid extra walking.
            for (RevCommit parent : commit.getParents()) {
                walk.markUninteresting(parent);
            }
            builder.accept(matches);
        }
    }

    return builder.build().flatMap(List::stream).max(Comparator.comparing(TaggedVersion::getVersion))
            .orElse(new TaggedVersion(Versions.VERSION_0, null));
}

From source file:org.cgiar.ccafs.marlo.action.annualReport.CrossCgiarPartnershipAction.java

public Long firstFlagship() {
    List<LiaisonInstitution> liaisonInstitutions = new ArrayList<>(loggedCrp.getLiaisonInstitutions().stream()
            .filter(c -> c.getCrpProgram() != null && c.isActive()
                    && c.getCrpProgram().getProgramType() == ProgramType.FLAGSHIP_PROGRAM_TYPE.getValue())
            .collect(Collectors.toList()));
    liaisonInstitutions.sort(Comparator.comparing(LiaisonInstitution::getAcronym));
    long liaisonInstitutionId = liaisonInstitutions.get(0).getId();
    return liaisonInstitutionId;
}

From source file:org.egov.pgr.service.ComplaintHistoryService.java

@ReadOnly
public List<HashMap<String, Object>> getHistory(Complaint complaint) {
    List<HashMap<String, Object>> historyTable = new ArrayList<>();
    State<Position> state = complaint.getState();
    HashMap<String, Object> map = new HashMap<>();
    map.put(DATE, state.getDateInfo());/*ww w .  j a v  a  2s . com*/
    map.put(COMMENT, defaultString(state.getComments()));
    map.put(STATUS, state.getValue());
    if ("Complaint is escalated".equals(state.getComments())) {
        map.put(UPDATEDBY, SYSTEMUSER);
        map.put(STATUS, ESCALATEDSTATUS);
    } else if (state.getLastModifiedBy().getType().equals(UserType.CITIZEN))
        map.put(UPDATEDBY, complaint.getComplainant().getName());
    else
        map.put(UPDATEDBY,
                defaultIfBlank(state.getSenderName(),
                        new StringBuilder().append(state.getLastModifiedBy().getUsername())
                                .append(DELIMITER_COLON).append(state.getLastModifiedBy().getName())
                                .toString()));
    map.put(UPDATEDUSERTYPE, state.getLastModifiedBy().getType());

    Position ownerPosition = state.getOwnerPosition();
    User user = state.getOwnerUser();
    if (user != null) {
        map.put(USER, user.getUsername() + DELIMITER_COLON + user.getName());
        map.put(USERTYPE, user.getType());
        Department department = eisCommonService.getDepartmentForUser(user.getId());
        map.put(DEPT, defaultString(department.getName()));
    } else if (ownerPosition != null && ownerPosition.getDeptDesig() != null) {
        List<Assignment> assignmentList = assignmentService.getAssignmentsForPosition(ownerPosition.getId(),
                new Date());
        Optional<Employee> employee = !assignmentList.isEmpty()
                ? Optional.ofNullable(assignmentList.get(0).getEmployee())
                : Optional.empty();
        map.put(USER,
                employee.isPresent()
                        ? new StringBuilder().append(employee.get().getUsername()).append(DELIMITER_COLON)
                                .append(employee.get().getName()).append(DELIMITER_COLON)
                                .append(ownerPosition.getDeptDesig().getDesignation().getName()).toString()
                        : new StringBuilder().append(NOASSIGNMENT).append(DELIMITER_COLON)
                                .append(ownerPosition.getName()).toString());
        map.put(USERTYPE, employee.isPresent() ? employee.get().getType() : EMPTY);
        map.put(DEPT, ownerPosition.getDeptDesig().getDepartment().getName());
    }
    historyTable.add(map);

    complaint.getStateHistory().stream()
            .sorted(Comparator.comparing(StateHistory<Position>::getLastModifiedDate).reversed())
            .forEach(stateHistory -> historyTable.add(constructComplaintHistory(complaint, stateHistory)));
    return historyTable;
}

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  www  . jav a2  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:com.netflix.metacat.connector.jdbc.services.JdbcConnectorDatabaseService.java

/**
 * {@inheritDoc}//from w  ww .  j a  v  a 2s .c  om
 */
@Override
public List<QualifiedName> listNames(@Nonnull final ConnectorRequestContext context,
        @Nonnull final QualifiedName name, @Nullable final QualifiedName prefix, @Nullable final Sort sort,
        @Nullable final Pageable pageable) {
    final String catalogName = name.getCatalogName();
    log.debug("Beginning to list database names for catalog {} for request {}", catalogName, context);

    try (final Connection connection = this.dataSource.getConnection()) {
        final DatabaseMetaData metaData = connection.getMetaData();
        final List<QualifiedName> names = Lists.newArrayList();

        try (final ResultSet schemas = prefix == null || StringUtils.isEmpty(prefix.getDatabaseName())
                ? metaData.getSchemas(connection.getCatalog(), null)
                : metaData.getSchemas(connection.getCatalog(),
                        prefix.getDatabaseName() + JdbcConnectorUtils.MULTI_CHARACTER_SEARCH)) {
            while (schemas.next()) {
                final String schemaName = schemas.getString("TABLE_SCHEM").toLowerCase(Locale.ENGLISH);
                // skip internal schemas
                if (!schemaName.equals("information_schema")) {
                    names.add(QualifiedName.ofDatabase(name.getCatalogName(), schemaName));
                }
            }
        }

        // Does user want sorting?
        if (sort != null) {
            // We can only really sort by the database name at this level so ignore SortBy field
            final Comparator<QualifiedName> comparator = Comparator.comparing(QualifiedName::getDatabaseName);
            JdbcConnectorUtils.sort(names, sort, comparator);
        }

        // Does user want pagination?
        final List<QualifiedName> results = JdbcConnectorUtils.paginate(names, pageable);

        log.debug("Finished listing database names for catalog {} for request {}", catalogName, context);
        return results;
    } catch (final SQLException se) {
        throw this.exceptionMapper.toConnectorException(se, name);
    }
}

From source file:com.github.aptd.simulation.elements.train.CDoor.java

@Override
protected boolean updatestate() {
    //debugPrintState();
    final EDoorState l_oldstate = m_state;
    final List<IMessage> l_entryrequests = m_input.get(EMessageType.PASSENGER_TO_DOOR_ENQUEUE_ENTRANCE);
    final List<IMessage> l_exitrequests = m_input.get(EMessageType.PASSENGER_TO_DOOR_ENQUEUE_EXIT);
    final List<IMessage> l_finished = m_input.get(EMessageType.PASSENGER_TO_DOOR_FINISHED);

    // enqueuing passengers (if queues are empty, passenger will get immediate access with nextpassengerifpossible() at the end)
    if (m_state != EDoorState.CLOSED_LOCKED) {
        l_entryrequests.stream().sorted(Comparator.comparing(msg -> msg.sender().id()))
                .forEachOrdered(msg -> m_entryqueue.add((IPassenger<?>) msg.sender()));
        l_exitrequests.stream().sorted(Comparator.comparing(msg -> msg.sender().id()))
                .forEachOrdered(msg -> m_exitqueue.add((IPassenger<?>) msg.sender()));
    } else {//  ww w .j a  v a 2 s. co m
        l_entryrequests.stream().sorted(Comparator.comparing(msg -> msg.sender().id())).forEachOrdered(
                msg -> output(new CMessage(this, msg.sender().id(), EMessageType.DOOR_TO_PASSENGER_REJECT)));
        l_exitrequests.stream().sorted(Comparator.comparing(msg -> msg.sender().id())).forEachOrdered(
                msg -> output(new CMessage(this, msg.sender().id(), EMessageType.DOOR_TO_PASSENGER_REJECT)));
    }

    // locking or unlocking
    handletrainmessages();

    // switches state from busy to free, but if queues are not empty, will become busy again with nextpassengerifpossible() at the end
    if (l_finished.size() > 1)
        throw new RuntimeException(m_id + " received multiple finished messages");
    if (!l_finished.isEmpty())
        passengerfinished(l_finished.get(0));

    // determine from which queue a passenger could be taken next: exit has priority over entry
    final Queue<IPassenger<?>> l_queue = m_exitqueue.isEmpty() ? m_entryqueue.isEmpty() ? null : m_entryqueue
            : m_exitqueue;

    // finish opening/closing process if applicable; switch to closable if door is open and has been unused for m_minfreetimetoclose seconds
    timedstatechangeifnecessary(l_queue);

    // if the door is in a permissible state, let the next passenger pass (or open the door first, if closed), if any
    nextpassengerifpossible(l_queue);

    //debugPrintState();
    return l_oldstate != m_state;
}

From source file:com.haulmont.cuba.core.app.EntityDiffManager.java

/**
 * Get diffs for entity properties/*from  w w w  . j ava  2 s. c  om*/
 *
 * @param diffView     View
 * @param firstEntity  First entity
 * @param secondEntity Second entity
 * @param diffBranch   Diff branch
 * @return Diff list
 */
protected List<EntityPropertyDiff> getPropertyDiffs(View diffView, Entity firstEntity, Entity secondEntity,
        Stack<Object> diffBranch) {
    List<EntityPropertyDiff> propertyDiffs = new LinkedList<>();

    MetaClass viewMetaClass = metadata.getSession().getClass(diffView.getEntityClass());
    MetaClass metaClass = extendedEntities.getEffectiveMetaClass(viewMetaClass);

    Collection<MetaPropertyPath> metaProperties = metadataTools.getViewPropertyPaths(diffView, metaClass);

    for (MetaPropertyPath metaPropertyPath : metaProperties) {
        MetaProperty metaProperty = metaPropertyPath.getMetaProperty();

        if (!metadataTools.isNotPersistent(metaProperty) && !metadataTools.isSystem(metaProperty)) {
            ViewProperty viewProperty = diffView.getProperty(metaProperty.getName());

            Object firstValue = firstEntity != null ? getPropertyValue(firstEntity, metaPropertyPath) : null;
            Object secondValue = secondEntity != null ? getPropertyValue(secondEntity, metaPropertyPath) : null;

            EntityPropertyDiff diff = getPropertyDifference(firstValue, secondValue, metaProperty, viewProperty,
                    diffBranch);
            if (diff != null)
                propertyDiffs.add(diff);
        }
    }

    Collection<CategoryAttribute> categoryAttributes = dynamicAttributesManagerAPI
            .getAttributesForMetaClass(metaClass);
    if (categoryAttributes != null) {
        for (CategoryAttribute categoryAttribute : categoryAttributes) {
            MetaPropertyPath metaPropertyPath = DynamicAttributesUtils.getMetaPropertyPath(metaClass,
                    categoryAttribute);
            MetaProperty metaProperty = metaPropertyPath.getMetaProperty();

            Object firstValue = firstEntity != null ? getPropertyValue(firstEntity, metaPropertyPath) : null;
            Object secondValue = secondEntity != null ? getPropertyValue(secondEntity, metaPropertyPath) : null;

            EntityPropertyDiff diff = getDynamicAttributeDifference(firstValue, secondValue, metaProperty,
                    categoryAttribute);
            if (diff != null)
                propertyDiffs.add(diff);
        }
    }

    Comparator<EntityPropertyDiff> comparator = Comparator.comparing(EntityPropertyDiff::getName);
    Collections.sort(propertyDiffs, comparator);

    return propertyDiffs;
}

From source file:io.spring.initializr.generator.CommandLineHelpGenerator.java

protected String generateDependencyTable(InitializrMetadata metadata) {
    String[][] dependencyTable = new String[metadata.getDependencies().getAll().size() + 1][];
    dependencyTable[0] = new String[] { "Id", "Description", "Required version" };
    int i = 1;//from   w w w. jav  a2 s  .  c om
    for (Dependency dep : metadata.getDependencies().getAll().stream()
            .sorted(Comparator.comparing(MetadataElement::getId)).collect(Collectors.toList())) {
        String[] data = new String[3];
        data[0] = dep.getId();
        data[1] = dep.getDescription() != null ? dep.getDescription() : dep.getName();
        data[2] = dep.getVersionRequirement();
        dependencyTable[i++] = data;
    }
    return TableGenerator.generate(dependencyTable);
}