Example usage for java.util Collections max

List of usage examples for java.util Collections max

Introduction

In this page you can find the example usage for java.util Collections max.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) 

Source Link

Document

Returns the maximum element of the given collection, according to the order induced by the specified comparator.

Usage

From source file:io.hops.transaction.context.BlockInfoContext.java

private BlockInfoContiguous findMaxBlk(BlockInfoContiguous.Finder bFinder, final Object[] params) {
    final long inodeId = (Long) params[0];
    Collection<BlockInfoContiguous> notRemovedBlks = Collections2.filter(filterValuesNotOnState(State.REMOVED),
            new Predicate<BlockInfoContiguous>() {
                @Override//from www  .  ja v a 2 s.  c o  m
                public boolean apply(BlockInfoContiguous input) {
                    return input.getInodeId() == inodeId;
                }
            });
    BlockInfoContiguous result = Collections.max(notRemovedBlks, BlockInfoContiguous.Order.ByBlockIndex);
    hit(bFinder, result, "inodeId", inodeId);
    return result;
}

From source file:org.apache.hadoop.hdfs.qjournal.client.QuorumJournalManager.java

/**
 * Run recovery/synchronization for a specific segment.
 * Postconditions://w  w w.j  a  v a  2s  .co m
 * <ul>
 * <li>This segment will be finalized on a majority
 * of nodes.</li>
 * <li>All nodes which contain the finalized segment will
 * agree on the length.</li>
 * </ul>
 * 
 * @param segmentTxId the starting txid of the segment
 * @throws IOException
 */
private void recoverUnclosedSegment(long segmentTxId) throws IOException {
    Preconditions.checkArgument(segmentTxId > 0);
    LOG.info("Beginning recovery of unclosed segment starting at txid " + segmentTxId);

    // Step 1. Prepare recovery
    QuorumCall<AsyncLogger, PrepareRecoveryResponseProto> prepare = loggers.prepareRecovery(segmentTxId);
    Map<AsyncLogger, PrepareRecoveryResponseProto> prepareResponses = loggers.waitForWriteQuorum(prepare,
            prepareRecoveryTimeoutMs, "prepareRecovery(" + segmentTxId + ")");
    LOG.info("Recovery prepare phase complete. Responses:\n" + QuorumCall.mapToString(prepareResponses));

    // Determine the logger who either:
    // a) Has already accepted a previous proposal that's higher than any
    //    other
    //
    //  OR, if no such logger exists:
    //
    // b) Has the longest log starting at this transaction ID

    // TODO: we should collect any "ties" and pass the URL for all of them
    // when syncing, so we can tolerate failure during recovery better.
    Entry<AsyncLogger, PrepareRecoveryResponseProto> bestEntry = Collections.max(prepareResponses.entrySet(),
            SegmentRecoveryComparator.INSTANCE);
    AsyncLogger bestLogger = bestEntry.getKey();
    PrepareRecoveryResponseProto bestResponse = bestEntry.getValue();

    // Log the above decision, check invariants.
    if (bestResponse.hasAcceptedInEpoch()) {
        LOG.info("Using already-accepted recovery for segment " + "starting at txid " + segmentTxId + ": "
                + bestEntry);
    } else if (bestResponse.hasSegmentState()) {
        LOG.info("Using longest log: " + bestEntry);
    } else {
        // None of the responses to prepareRecovery() had a segment at the given
        // txid. This can happen for example in the following situation:
        // - 3 JNs: JN1, JN2, JN3
        // - writer starts segment 101 on JN1, then crashes before
        //   writing to JN2 and JN3
        // - during newEpoch(), we saw the segment on JN1 and decide to
        //   recover segment 101
        // - before prepare(), JN1 crashes, and we only talk to JN2 and JN3,
        //   neither of which has any entry for this log.
        // In this case, it is allowed to do nothing for recovery, since the
        // segment wasn't started on a quorum of nodes.

        // Sanity check: we should only get here if none of the responses had
        // a log. This should be a postcondition of the recovery comparator,
        // but a bug in the comparator might cause us to get here.
        for (PrepareRecoveryResponseProto resp : prepareResponses.values()) {
            assert !resp.hasSegmentState() : "One of the loggers had a response, but no best logger "
                    + "was found.";
        }

        LOG.info("None of the responders had a log to recover: " + QuorumCall.mapToString(prepareResponses));
        return;
    }

    SegmentStateProto logToSync = bestResponse.getSegmentState();
    assert segmentTxId == logToSync.getStartTxId();

    // Sanity check: none of the loggers should be aware of a higher
    // txid than the txid we intend to truncate to
    for (Map.Entry<AsyncLogger, PrepareRecoveryResponseProto> e : prepareResponses.entrySet()) {
        AsyncLogger logger = e.getKey();
        PrepareRecoveryResponseProto resp = e.getValue();

        if (resp.hasLastCommittedTxId() && resp.getLastCommittedTxId() > logToSync.getEndTxId()) {
            throw new AssertionError("Decided to synchronize log to " + logToSync + " but logger " + logger
                    + " had seen txid " + resp.getLastCommittedTxId() + " committed");
        }
    }

    URL syncFromUrl = bestLogger.buildURLToFetchLogs(segmentTxId);

    QuorumCall<AsyncLogger, Void> accept = loggers.acceptRecovery(logToSync, syncFromUrl);
    loggers.waitForWriteQuorum(accept, acceptRecoveryTimeoutMs,
            "acceptRecovery(" + TextFormat.shortDebugString(logToSync) + ")");

    // If one of the loggers above missed the synchronization step above, but
    // we send a finalize() here, that's OK. It validates the log before
    // finalizing. Hence, even if it is not "in sync", it won't incorrectly
    // finalize.
    QuorumCall<AsyncLogger, Void> finalize = loggers.finalizeLogSegment(logToSync.getStartTxId(),
            logToSync.getEndTxId());
    loggers.waitForWriteQuorum(finalize, finalizeSegmentTimeoutMs,
            String.format("finalizeLogSegment(%s-%s)", logToSync.getStartTxId(), logToSync.getEndTxId()));
}

From source file:hu.tbognar76.apking.ApKing.java

private void reportDuplications(boolean toDelete) {

    for (Map.Entry<String, ArrayList<ApkInfo>> entry : this.packageHash.entrySet()) {
        // String key = entry.getKey();
        ArrayList<ApkInfo> value = entry.getValue();
        if (value.size() > 1) {
            ArrayList<CApkInfo> cvalue = new ArrayList<ApKing.CApkInfo>();
            System.out.println("");

            List<Version> versions = new ArrayList<Version>();

            boolean versionerror = false;
            boolean versionerror2 = false;

            for (ApkInfo ai : value) {

                CApkInfo cai = new CApkInfo();

                cai.apkinfo = ai;// w  ww .  j  a  v  a 2s . c om

                // System.out.println(ai.fullpath + "     " + ai.version);
                try {
                    versions.add(new Version(ai.version));

                } catch (Exception e) {
                    versionerror = true;
                }

                try {
                    cai.cmp = new ComparableVersion(ai.version);
                } catch (Exception e) {
                    versionerror2 = true;
                }
                cvalue.add(cai);

            }

            if (versionerror2) {
                System.out.println("BAD VERSION FORMAT 2");
                for (ApkInfo ais : value) {
                    System.out.println("#del " + ais.fullpath);
                }

            } else {
                CApkInfo maxi = Collections.max(cvalue, new Comparator<CApkInfo>() {
                    @Override
                    public int compare(CApkInfo left, CApkInfo right) {
                        return left.cmp.compareTo(right.cmp);
                    }
                });
                maxi.max = true;

                String warning = "";
                if (versionerror || versionerror2) {
                    warning = "WARNING!! ";
                }

                String vers = "";
                for (CApkInfo aic : cvalue) {
                    if (aic.max) {
                        vers = vers + "-->" + aic.apkinfo.version + "<-- , ";
                    } else {
                        vers = vers + aic.apkinfo.version + " , ";
                    }
                }
                System.out.println("::" + warning + maxi.apkinfo.name + " // " + vers);

                for (CApkInfo aic : cvalue) {
                    // String max ;
                    if (aic.max) {
                        // max = "rem #";
                        // A LEGUJABB
                        System.out.println("!OK " + aic.apkinfo.fullpath);

                    } else {
                        // REGEBBI , TOROLNI KELL (MOVE TO DELETEFOLDER)
                        System.out.println("del " + aic.apkinfo.fullpath);

                        if (toDelete) {
                            String renamedfile = this.init.deletePath + "/"
                                    + FilenameUtils.getName(aic.apkinfo.fullpath);
                            File file = new File(aic.apkinfo.fullpath);
                            if (file.renameTo(new File(renamedfile))) {

                            } else {
                                System.out.println("File is failed to move!" + renamedfile);
                            }
                        }
                    }

                }

            }
            // System.out.println("MAX: " + maxi.apkinfo.version +
            // "   "+maxi.apkinfo.filename);

        }
        // do stuff
    }

}

From source file:pt.ist.fenix.ui.struts.action.koha.ExportUserInfoForKoha.java

private static StudentCurricularPlan findMaxStudentCurricularPlan(
        final Set<StudentCurricularPlan> studentCurricularPlans) {
    return Collections.max(studentCurricularPlans, new Comparator<StudentCurricularPlan>() {

        @Override//from  ww w .  j a  va2s . co  m
        public int compare(final StudentCurricularPlan o1, final StudentCurricularPlan o2) {
            final DegreeType degreeType1 = o1.getDegreeType();
            final DegreeType degreeType2 = o2.getDegreeType();
            if (degreeType1 == degreeType2) {
                final YearMonthDay yearMonthDay1 = o1.getStartDateYearMonthDay();
                final YearMonthDay yearMonthDay2 = o2.getStartDateYearMonthDay();
                final int c = yearMonthDay1.compareTo(yearMonthDay2);
                return c == 0 ? DomainObjectUtil.COMPARATOR_BY_ID.compare(o1, o2) : c;
            } else {
                return degreeType1.compareTo(degreeType2);
            }
        }

    });
}

From source file:com.turn.griffin.GriffinLibCacheUtil.java

private long getLatestLocalVersion(String dir) {

    File ObjDir = new File(dir);
    List<File> versions = Arrays.asList(ObjDir.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY));
    String latest = Collections.max(versions, new Comparator<File>() {
        @Override/*  ww  w.j  a  va2 s. c o  m*/
        public int compare(File a, File b) {
            return a.getName().compareTo(b.getName());
        }
    }).getName();
    return Long.parseLong(latest);
}

From source file:org.squashtest.tm.domain.campaign.Campaign.java

private Iteration getLastIteration() {
    if (getIterations().isEmpty()) {
        return null;
    } else {/*from  w  ww. j a va2s  .  c  o m*/
        return Collections.max(getIterations(),
                CascadingAutoDateComparatorBuilder.buildIterationActualEndOrder());
    }
}

From source file:com.example.android.camera2basic.Fragment.Camera2BasicFragment.java

/**
 * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
 * is at least as large as the respective texture view size, and that is at most as large as the
 * respective max size, and whose aspect ratio matches with the specified value. If such size
 * doesn't exist, choose the largest one that is at most as large as the respective max size,
 * and whose aspect ratio matches with the specified value.
 *
 * @param choices           The list of sizes that the camera supports for the intended output
 *                          class// w  ww . j av  a  2 s.  com
 * @param textureViewWidth  The width of the texture view relative to sensor coordinate
 * @param textureViewHeight The height of the texture view relative to sensor coordinate
 * @param maxWidth          The maximum width that can be chosen
 * @param maxHeight         The maximum height that can be chosen
 * @param aspectRatio       The aspect ratio
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight, int maxWidth,
        int maxHeight, Size aspectRatio) {

    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    // Collect the supported resolutions that are smaller than the preview Surface
    List<Size> notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight
                && option.getHeight() == option.getWidth() * h / w) {
            if (option.getWidth() >= textureViewWidth && option.getHeight() >= textureViewHeight) {
                bigEnough.add(option);
            } else {
                notBigEnough.add(option);
            }
        }
    }

    // Pick the smallest of those big enough. If there is no one big enough, pick the
    // largest of those not big enough.
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
        Log.e(TAG, "Couldn't find any suitable preview size");
        //            Log.d(TAG,choices[0].getWidth()+" size "+choices[0].getHeight());
        return choices[0];
    }
}

From source file:org.odk.collect.android.fragments.Camera2Fragment.java

/**
 * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
 * is at least as large as the respective texture view size, and that is at most as large as the
 * respective max size, and whose aspect ratio matches with the specified value. If such size
 * doesn't exist, choose the largest one that is at most as large as the respective max size,
 * and whose aspect ratio matches with the specified value.
 *
 * @param choices           The list of sizes that the camera supports for the intended output
 *                          class//from   ww w. j av a 2s  . c  o m
 * @param textureViewWidth  The width of the texture view relative to sensor coordinate
 * @param textureViewHeight The height of the texture view relative to sensor coordinate
 * @param maxWidth          The maximum width that can be chosen
 * @param maxHeight         The maximum height that can be chosen
 * @param aspectRatio       The aspect ratio
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight, int maxWidth,
        int maxHeight, Size aspectRatio) {

    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    // Collect the supported resolutions that are smaller than the preview Surface
    List<Size> notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight
                && option.getHeight() == option.getWidth() * h / w) {
            if (option.getWidth() >= textureViewWidth && option.getHeight() >= textureViewHeight) {
                bigEnough.add(option);
            } else {
                notBigEnough.add(option);
            }
        }
    }

    // Pick the smallest of those big enough. If there is no one big enough, pick the
    // largest of those not big enough.
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
        return choices[0];
    }
}

From source file:net.sourceforge.fenixedu.domain.student.Student.java

public Registration getLastActiveRegistration() {
    List<Registration> activeRegistrations = getActiveRegistrations();
    return activeRegistrations.isEmpty() ? null
            : (Registration) Collections.max(activeRegistrations, Registration.COMPARATOR_BY_START_DATE);
}

From source file:camera2basic.Camera2BasicFragment.java

/**
 * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
 * is at least as large as the respective texture view size, and that is at most as large as the
 * respective max size, and whose aspect ratio matches with the specified value. If such size
 * doesn't exist, choose the largest one that is at most as large as the respective max size,
 * and whose aspect ratio matches with the specified value.
 *
 * @param choices           The list of sizes that the camera supports for the intended output
 *                          class//from  www  .  j a  v  a  2 s . com
 * @param textureViewWidth  The width of the texture view relative to sensor coordinate
 * @param textureViewHeight The height of the texture view relative to sensor coordinate
 * @param maxWidth          The maximum width that can be chosen
 * @param maxHeight         The maximum height that can be chosen
 * @param aspectRatio       The aspect ratio
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight, int maxWidth,
        int maxHeight, Size aspectRatio) {

    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = new ArrayList<>();
    // Collect the supported resolutions that are smaller than the preview Surface
    List<Size> notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight
                && option.getHeight() == option.getWidth() * h / w) {
            if (option.getWidth() >= textureViewWidth && option.getHeight() >= textureViewHeight) {
                bigEnough.add(option);
            } else {
                notBigEnough.add(option);
            }
        }
    }

    // Pick the smallest of those big enough. If there is no one big enough, pick the
    // largest of those not big enough.
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0) {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else {
        Log.e(TAG, "Couldn't find any suitable preview size");
        return choices[0];
    }
}