Example usage for java.util List sort

List of usage examples for java.util List sort

Introduction

In this page you can find the example usage for java.util List 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:com.kurtraschke.nyctrtproxy.services.TripUpdateProcessor.java

public List<GtfsRealtime.TripUpdate> processFeed(Integer feedId, GtfsRealtime.FeedMessage fm,
        MatchMetrics totalMetrics) {/*  www  .j  a va  2s . co  m*/

    long timestamp = fm.getHeader().getTimestamp();

    MatchMetrics feedMetrics = new MatchMetrics();
    feedMetrics.reportLatency(timestamp);

    if (_latencyLimit > 0 && feedMetrics.getLatency() > _latencyLimit) {
        _log.info("Feed {} ignored, too high latency = {}", feedId, feedMetrics.getLatency());
        if (_listener != null)
            _listener.reportMatchesForSubwayFeed(feedId.toString(), feedMetrics, _cloudwatchNamespace);
        return Collections.emptyList();
    }

    final Map<String, String> realtimeToStaticRouteMap = _realtimeToStaticRouteMapByFeed.getOrDefault(feedId,
            Collections.emptyMap());

    int nExpiredTus = 0, nTotalRecords = 0;

    // Read in trip updates per route. Skip trip updates that have too stale of data.
    Multimap<String, GtfsRealtime.TripUpdate> tripUpdatesByRoute = ArrayListMultimap.create();
    for (GtfsRealtime.FeedEntity entity : fm.getEntityList()) {
        if (entity.hasTripUpdate()) {
            GtfsRealtime.TripUpdate tu = entity.getTripUpdate();
            if (expiredTripUpdate(tu, fm.getHeader().getTimestamp())) {
                nExpiredTus++;
            } else {
                String routeId = tu.getTrip().getRouteId();
                routeId = realtimeToStaticRouteMap.getOrDefault(routeId, routeId);
                tripUpdatesByRoute.put(routeId, tu);
            }
            nTotalRecords++;
        }
    }
    reportRecordsIn(nTotalRecords, nExpiredTus, totalMetrics, feedMetrics);

    List<GtfsRealtime.TripUpdate> ret = Lists.newArrayList();

    for (GtfsRealtimeNYCT.TripReplacementPeriod trp : fm.getHeader()
            .getExtension(GtfsRealtimeNYCT.nyctFeedHeader).getTripReplacementPeriodList()) {
        if (_routeBlacklistByFeed.getOrDefault(feedId, Collections.emptySet()).contains(trp.getRouteId()))
            continue;
        GtfsRealtime.TimeRange range = trp.getReplacementPeriod();

        Date start = range.hasStart() ? new Date(range.getStart() * 1000)
                : earliestTripStart(tripUpdatesByRoute.values());
        Date end = range.hasEnd() ? new Date(range.getEnd() * 1000)
                : new Date(fm.getHeader().getTimestamp() * 1000);

        // All route IDs in this trip replacement period
        Set<String> routeIds = Arrays.stream(trp.getRouteId().split(", ?"))
                .map(routeId -> realtimeToStaticRouteMap.getOrDefault(routeId, routeId))
                .collect(Collectors.toSet());

        for (String routeId : routeIds) {
            String newRouteId = _addToTripReplacementPeriodByRoute.get(routeId);
            if (newRouteId != null)
                routeIds.add(newRouteId);
        }

        // Kurt's trip matching algorithm (ActivatedTripMatcher) requires calculating currently-active static trips at this point.
        _tripMatcher.initForFeed(start, end, routeIds);

        for (String routeId : routeIds) {

            MatchMetrics routeMetrics = new MatchMetrics();

            Multimap<String, TripMatchResult> matchesByTrip = ArrayListMultimap.create();
            Collection<GtfsRealtime.TripUpdate> tripUpdates = tripUpdatesByRoute.get(routeId);
            routeMetrics.reportRecordsIn(tripUpdates.size());
            for (GtfsRealtime.TripUpdate tu : tripUpdates) {
                GtfsRealtime.TripUpdate.Builder tub = GtfsRealtime.TripUpdate.newBuilder(tu);
                GtfsRealtime.TripDescriptor.Builder tb = tub.getTripBuilder();

                // rewrite route ID for some routes
                tb.setRouteId(realtimeToStaticRouteMap.getOrDefault(tb.getRouteId(), tb.getRouteId()));

                // remove timepoints not in GTFS... in some cases this means there may be no STUs left (ex. H shuttle at H19S.)
                removeTimepoints(tub);

                // get ID which consists of route, direction, origin-departure time, possibly a path identifier (for feed 1.)
                NyctTripId rtid = NyctTripId.buildFromTripDescriptor(tb, _routesWithReverseRTDirections);

                // If we were able to parse the trip ID, there are various fixes
                // we may need to apply.
                if (rtid != null) {

                    // Fix stop IDs which don't include direction
                    tub.getStopTimeUpdateBuilderList().forEach(stub -> {
                        if (!(stub.getStopId().endsWith("N") || stub.getStopId().endsWith("S"))) {
                            stub.setStopId(stub.getStopId() + rtid.getDirection());
                        } else if (_routesWithReverseRTDirections.contains(tb.getRouteId())) {
                            String stopId = stub.getStopId();
                            stub.setStopId(stopId.substring(0, stopId.length() - 1) + rtid.getDirection());
                        }
                        if (_stopIdTransformStrategy != null) {
                            String stopId = stub.getStopId();
                            stopId = _stopIdTransformStrategy.transform(rtid.getRouteId(), rtid.getDirection(),
                                    stopId);
                            stub.setStopId(stopId);
                        }
                    });

                    // Re-set the trip ID to the parsed trip ID; coerces IDs to a uniform format.
                    // If the trip is matched, the ID will be rewritten again to the corresponding static trip ID below.
                    tb.setTripId(rtid.toString());
                } else {
                    _log.error("invalid trip_id={} train_id={}", tb.getTripId(),
                            tb.getExtension(GtfsRealtimeNYCT.nyctTripDescriptor).getTrainId());
                }

                // Some routes have start date set incorrectly
                if (tb.getStartDate().length() > 8) {
                    tb.setStartDate(fixedStartDate(tb));
                }

                TripMatchResult result = _tripMatcher.match(tub, rtid, fm.getHeader().getTimestamp());
                matchesByTrip.put(result.getTripId(), result);
            }

            // For TUs that match to same trip - possible they should be merged (route D has mid-line relief points where trip ID changes)
            // If they are NOT merged, then drop the matches for the worse ones
            for (Collection<TripMatchResult> matches : matchesByTrip.asMap().values()) {
                if (!tryMergeResult(matches) && matches.size() > 1 && !_allowDuplicates) {
                    List<TripMatchResult> dups = new ArrayList<>(matches);
                    dups.sort(Collections.reverseOrder());
                    TripMatchResult best = dups.get(0);
                    for (int i = 1; i < dups.size(); i++) {
                        TripMatchResult result = dups.get(i);
                        _log.debug(
                                "dropping duplicate in static trip={}, RT trip={} ({}). Better trip is {} ({})",
                                best.getTripId(), result.getRtTripId(), result.getStatus(), best.getRtTripId(),
                                best.getStatus());
                        result.setStatus(Status.NO_MATCH);
                        result.setResult(null);
                    }
                }
            }

            Set<String> matchedTripIds = new HashSet<>();
            // Read out results of matching. If there is a match, rewrite TU's trip ID. Add TU to return list.
            for (TripMatchResult result : matchesByTrip.values()) {
                if (!result.getStatus().equals(Status.MERGED)) {
                    GtfsRealtime.TripUpdate.Builder tub = result.getTripUpdateBuilder();
                    GtfsRealtime.TripDescriptor.Builder tb = tub.getTripBuilder();
                    if (result.hasResult() && (result.getTripUpdate().getStopTimeUpdateCount() == 0
                            || !result.stopsMatchToEnd())) {
                        _log.info("no stop match rt={} static={} {}",
                                result.getTripUpdate().getTrip().getTripId(),
                                result.getResult().getTrip().getId().getId(),
                                (result.getResult().getStopTimes().get(0).getDepartureTime() / 60) * 100);
                        result.setStatus(Status.NO_MATCH);
                        result.setResult(null);
                    }
                    if (result.hasResult()) {
                        ActivatedTrip at = result.getResult();
                        String staticTripId = at.getTrip().getId().getId();
                        _log.debug("matched {} -> {}", tb.getTripId(), staticTripId);
                        tb.setTripId(staticTripId);
                        removeTimepoints(at, tub);
                        matchedTripIds.add(staticTripId);
                    } else {
                        _log.debug("unmatched: {} due to {}", tub.getTrip().getTripId(), result.getStatus());
                        tb.setScheduleRelationship(GtfsRealtime.TripDescriptor.ScheduleRelationship.ADDED);
                        // ignore ADDED trips without stops
                        if (tub.getStopTimeUpdateCount() == 0)
                            continue;
                        // Trip Headsign and direction
                        String stopId = result.getRtLastStop();
                        String tripHeadsign = _tripActivator.getStopNameForId(stopId);
                        String nsDirection = NyctTripId
                                .buildFromTripDescriptor(tub.getTrip(), _routesWithReverseRTDirections)
                                .getDirection();
                        String tripDirection = "S".equals(nsDirection) ? "1" : "0";
                        GtfsRealtimeOneBusAway.OneBusAwayTripUpdate.Builder obaTripUpdate = GtfsRealtimeOneBusAway.OneBusAwayTripUpdate
                                .newBuilder();
                        if (StringUtils.isNotBlank(tripHeadsign)) {
                            obaTripUpdate.setTripHeadsign(tripHeadsign);
                            //Stop Headsign
                            if (_directionsService != null)
                                _directionsService.fillStopHeadSigns(tub.getStopTimeUpdateBuilderList());
                        }
                        obaTripUpdate.setTripDirection(tripDirection);
                        tub.setExtension(GtfsRealtimeOneBusAway.obaTripUpdate, obaTripUpdate.build());
                    }
                    tub.setTimestamp(timestamp);
                    TripUpdate tripUpdate = tub.build();
                    ret.add(tripUpdate);
                }

                routeMetrics.add(result);
                feedMetrics.add(result);
                totalMetrics.add(result);
            }

            if (_cancelUnmatchedTrips) {
                Iterator<ActivatedTrip> staticTrips = _tripActivator
                        .getTripsForRangeAndRoute(start, end, routeId).iterator();
                while (staticTrips.hasNext()) {
                    ActivatedTrip at = staticTrips.next();
                    if (!matchedTripIds.contains(at.getTrip().getId().getId())) {
                        long time = fm.getHeader().getTimestamp();
                        if (at.activeFor(trp, time)) {
                            TripUpdate.Builder tub = TripUpdate.newBuilder();
                            TripDescriptor.Builder tdb = tub.getTripBuilder();
                            tdb.setTripId(at.getTrip().getId().getId());
                            tdb.setRouteId(at.getTrip().getRoute().getId().getId());
                            tdb.setStartDate(at.getServiceDate().getAsString());
                            tdb.setScheduleRelationship(ScheduleRelationship.CANCELED);
                            ret.add(tub.build());

                            routeMetrics.addCancelled();
                            feedMetrics.addCancelled();
                            totalMetrics.addCancelled();
                        }
                    }
                }
            }

            if (_listener != null)
                _listener.reportMatchesForRoute(routeId, routeMetrics, _cloudwatchNamespace);
        }
    }

    if (_listener != null)
        _listener.reportMatchesForSubwayFeed(feedId.toString(), feedMetrics, _cloudwatchNamespace);

    _log.info("feed={}, expired TUs={}", feedId, nExpiredTus);
    return ret;
}

From source file:org.silverpeas.core.notification.user.delayed.delegate.DelayedNotificationDelegate.java

private DelayedNotificationSyntheseData buildSynthese(final List<DelayedNotificationData> delayedNotifications)
        throws AdminException {

    // Result/*from  ww  w . jav a 2  s  . c o  m*/
    final DelayedNotificationSyntheseData synthese = initializeSynthese(delayedNotifications);

    // Indexing
    final Map<NotificationResourceData, List<DelayedNotificationData>> resourcesAndNotifications = new HashMap<>();
    for (final DelayedNotificationData delayedNotificationData : delayedNotifications) {
        putAddList(resourcesAndNotifications, delayedNotificationData.getResource(), delayedNotificationData);
    }

    // Sorting indexes
    final List<NotificationResourceData> orderedResources = new ArrayList<>(resourcesAndNotifications.keySet());
    orderedResources.sort(getResourceComparator());

    // Browsing all the delayed notifications to build the synthese
    for (final NotificationResourceData resource : orderedResources) {

        // Performing a resource and her associated notifications
        prepareSyntheseResourceAndNotifications(synthese, resource, resourcesAndNotifications.get(resource));
    }

    // Building the final message
    synthese.setMessage(buildMessage(synthese));

    // Returning the initialized synthese
    return synthese;
}

From source file:net.dv8tion.jda.core.entities.impl.GuildImpl.java

@Override
public List<VoiceChannel> getVoiceChannels() {
    List<VoiceChannel> channels = new ArrayList<>(voiceChannels.valueCollection());
    channels.sort(Comparator.reverseOrder());
    return Collections.unmodifiableList(channels);
}

From source file:org.sakaiproject.gradebookng.tool.model.GbGradebookData.java

private List<String[]> courseGrades() {
    final List<String[]> result = new ArrayList<>();

    final Map<String, Double> gradeMap = this.settings.getSelectedGradingScaleBottomPercents();
    final List<String> ascendingGrades = new ArrayList<>(gradeMap.keySet());
    ascendingGrades.sort(new Comparator<String>() {
        @Override/*from ww  w.jav a2 s .  com*/
        public int compare(final String a, final String b) {
            return new CompareToBuilder().append(gradeMap.get(a), gradeMap.get(b)).toComparison();
        }
    });

    for (final GbStudentGradeInfo studentGradeInfo : GbGradebookData.this.studentGradeInfoList) {
        // String[0] = A+ (95%) [133/140] -- display string
        // String[1] = 95 -- raw percentage for sorting
        // String[2] = 1 -- '1' if an override, '0' if calculated
        final String[] gradeData = new String[3];

        final GbCourseGrade gbCourseGrade = studentGradeInfo.getCourseGrade();
        final CourseGrade courseGrade = gbCourseGrade.getCourseGrade();

        gradeData[0] = gbCourseGrade.getDisplayString();

        if (StringUtils.isNotBlank(courseGrade.getEnteredGrade())) {
            gradeData[2] = "1";
        } else {
            gradeData[2] = "0";
        }

        if (StringUtils.isNotBlank(courseGrade.getEnteredGrade())) {
            Double mappedGrade = this.courseGradeMap.get(courseGrade.getEnteredGrade());
            if (mappedGrade == null) {
                mappedGrade = new Double(0);
            }
            gradeData[1] = FormatHelper.formatGradeForDisplay(mappedGrade);
        } else {
            if (courseGrade.getPointsEarned() == null) {
                gradeData[1] = "0";
            } else {
                gradeData[1] = FormatHelper.formatGradeForDisplay(courseGrade.getCalculatedGrade());
            }
        }

        result.add(gradeData);
    }

    return result;
}

From source file:org.opencb.biodata.tools.variant.converter.VariantToProtoVcfRecord.java

/**
 * Creates a sorted list of strings from the INFO KEYs
 *
 * @return {@link List}//ww  w.  jav a 2 s  .  c  o  m
 * @param keys
 */
private List<Integer> encodeInfoKeys(Collection<String> keys) {
    // sorted key list
    List<Integer> idxKeys = new ArrayList<>(keys.size());
    for (String key : keys) {
        if (!IGNORED_KEYS.contains(key)) {
            Integer idx = infoKeyIndexMap.get(key);
            if (idx != null) {
                idxKeys.add(idx);
            } else {
                throw new IllegalArgumentException("Unknown key value " + key);
            }
        }
    }
    idxKeys.sort(Integer::compareTo);
    return idxKeys;
}

From source file:org.dspace.content.RelationshipServiceImpl.java

private void handleCreationPlaces(Context context, Relationship relationship) throws SQLException {
    List<Relationship> leftRelationships;
    List<Relationship> rightRelationships;
    leftRelationships = findByItemAndRelationshipType(context, relationship.getLeftItem(),
            relationship.getRelationshipType(), true);
    rightRelationships = findByItemAndRelationshipType(context, relationship.getRightItem(),
            relationship.getRelationshipType(), false);
    leftRelationships.sort((o1, o2) -> o2.getLeftPlace() - o1.getLeftPlace());
    rightRelationships.sort((o1, o2) -> o2.getRightPlace() - o1.getRightPlace());

    if (!leftRelationships.isEmpty()) {
        relationship.setLeftPlace(leftRelationships.get(0).getLeftPlace() + 1);
    } else {/*from  w  w w. j a v  a 2  s .c o m*/
        relationship.setLeftPlace(0);
    }

    if (!rightRelationships.isEmpty()) {
        relationship.setRightPlace(rightRelationships.get(0).getRightPlace() + 1);
    } else {
        relationship.setRightPlace(0);
    }
}

From source file:com.btkelly.gnag.tasks.GnagReportTask.java

private void postViolationComments(@NotNull final Set<Violation> violations) {
    final Set<Violation> violationsWithAllLocationInformation = ViolationsUtil
            .hasViolationWithAllLocationInformation(violations);

    if (StringUtils.isBlank(prSha) || violationsWithAllLocationInformation.isEmpty()) {
        gitHubApi.postGitHubPRCommentAsync(ViolationsFormatter.getHtmlStringForAggregatedComment(violations));
        return;/*from   w ww. j av  a 2  s . com*/
    }

    final List<Diff> diffs = gitHubApi.getPRDiffsSync();

    if (diffs.isEmpty()) {
        gitHubApi.postGitHubPRCommentAsync(ViolationsFormatter.getHtmlStringForAggregatedComment(violations));
        return;
    }

    final Map<Violation, PRLocation> violationPRLocationMap = ViolationsUtil
            .getPRLocationsForViolations(violations, diffs);

    final List<Violation> violationsWithValidLocationInfo = new ArrayList<>();
    final Set<Violation> violationsWithMissingOrInvalidLocationInfo = new HashSet<>();

    for (final Map.Entry<Violation, PRLocation> entry : violationPRLocationMap.entrySet()) {
        final Violation violation = entry.getKey();
        final PRLocation prLocation = entry.getValue();

        if (prLocation != null) {
            violationsWithValidLocationInfo.add(violation);
        } else {
            violationsWithMissingOrInvalidLocationInfo.add(violation);
        }
    }

    violationsWithValidLocationInfo.sort(Violation.COMMENT_POSTING_COMPARATOR);

    violationsWithValidLocationInfo.stream()
            .forEach(violation -> gitHubApi.postGitHubInlineCommentSync(
                    ViolationFormatter.getHtmlStringForInlineComment(violation), prSha,
                    violationPRLocationMap.get(violation)));

    if (!violationsWithMissingOrInvalidLocationInfo.isEmpty()) {
        try {
            /*
             * Try to post the aggregate comment _strictly after_ all individual comments. GitHub seems to round
             * post times to the nearest second, so delaying by one whole second should be sufficient here.
             */
            Thread.sleep(TimeUnit.SECONDS.toMillis(1));
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }

        gitHubApi.postGitHubPRCommentAsync(ViolationsFormatter
                .getHtmlStringForAggregatedComment(violationsWithMissingOrInvalidLocationInfo));
    }
}

From source file:org.apache.solr.handler.component.HttpShardHandlerFactory.java

ReplicaListTransformer getReplicaListTransformer(final SolrQueryRequest req) {
    final SolrParams params = req.getParams();

    if (params.getBool(CommonParams.PREFER_LOCAL_SHARDS, false)) {
        final CoreDescriptor coreDescriptor = req.getCore().getCoreDescriptor();
        final ZkController zkController = coreDescriptor.getCoreContainer().getZkController();
        final String preferredHostAddress = (zkController != null) ? zkController.getBaseUrl() : null;
        if (preferredHostAddress == null) {
            log.warn("Couldn't determine current host address to prefer local shards");
        } else {/*from   w w  w .j  a va  2 s .c om*/
            return new ShufflingReplicaListTransformer(r) {
                @Override
                public void transform(List<?> choices) {
                    if (choices.size() > 1) {
                        super.transform(choices);
                        if (log.isDebugEnabled()) {
                            log.debug("Trying to prefer local shard on {} among the choices: {}",
                                    preferredHostAddress, Arrays.toString(choices.toArray()));
                        }
                        choices.sort(new IsOnPreferredHostComparator(preferredHostAddress));
                        if (log.isDebugEnabled()) {
                            log.debug("Applied local shard preference for choices: {}",
                                    Arrays.toString(choices.toArray()));
                        }
                    }
                }
            };
        }
    }

    return shufflingReplicaListTransformer;
}

From source file:app.NewJFrame.java

private void showTable(List<WordStatistic> was) {
    TableModel model = new WordStatisticTableModel(was);
    jTable1.setModel(model);//ww w .  j a  v  a  2s  .co  m
    RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    jTable1.setRowSorter(sorter);
    was.sort(null);
}

From source file:com.haulmont.cuba.gui.data.impl.CollectionDatasourceImpl.java

protected void doSort() {
    @SuppressWarnings("unchecked")
    List<T> list = new ArrayList<>(data.values());
    list.sort(createEntityComparator());
    data.clear();//www  .  j  av  a2  s  .  co m
    for (T t : list) {
        data.put(t.getId(), t);
    }
}