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:net.sourceforge.fenixedu.domain.ExecutionYear.java

public ExecutionSemester getLastExecutionPeriod() {
    return Collections.max(this.getExecutionPeriodsSet(), ExecutionSemester.COMPARATOR_BY_SEMESTER_AND_YEAR);
}

From source file:com.tenth.space.ui.fragment.HomeFragment.java

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);// ww  w  . java2s.c o  m
            } else {
                notBigEnough.add(option);
            }
        }
    }
    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];
    }
}

From source file:br.upe.ecomp.doss.algorithm.apso.APSO.java

protected void doElitistLearningStrategy() {
    RandomData random = new RandomDataImpl();
    APSOParticle[] particles = (APSOParticle[]) getParticles();

    List<APSOParticle> apsoParticles = Arrays.asList(particles);
    APSOParticle bestParticle = Collections.max(apsoParticles, new ComparatorMaximumFitness());

    // Dimension that can be changed if the best particle fitness improves after the change
    int dimensionChange = random.nextInt(0, getProblem().getDimensionsNumber() - 1);
    double[] currentBestPosition = bestParticle.getBestPosition();

    // Standard Deviation of the Gaussian Distribution
    // TODO usar esse decaimento linear pode ser ruim para ambientes dinamicos
    double learningElitistRate = sigmaMax - (sigmaMax - sigmaMin) * (this.getIterations() / getMaxIterations());

    // Changes position in only one dimension
    // if(EnumEvolutionaryState.CONVERGENCE) TODO testar com e sem esta condicao
    double newDimensionPosition = currentBestPosition[dimensionChange]
            + (getProblem().getUpperBound(dimensionChange) - getProblem().getLowerBound(dimensionChange))
                    * random.nextGaussian(0, learningElitistRate);

    // TODO verificar se nao extrapolou o limite do espaco de busca
    double[] newPosition = currentBestPosition.clone();
    newPosition[dimensionChange] = newDimensionPosition;

    double currentBestFitness = bestParticle.getBestFitness();
    double newFitness = getProblem().getFitness(newPosition);

    // If the change improves the fitness then update the best particle with the new position,
    // else update the worst particle with the new position.
    if (getProblem().isFitnessBetterThan(currentBestFitness, newFitness)) {
        bestParticle.updateBestPosition(newPosition.clone(), newFitness);
        bestParticle.updateCurrentPosition(newPosition.clone(), newFitness);
    } else {/*  www. j a va  2s.c  o m*/
        PSOParticle worstParticle = Collections.min(apsoParticles, new ComparatorMaximumFitness());
        worstParticle.updateCurrentPosition(newPosition.clone(), newFitness);
        worstParticle.updatePBest(getProblem());
    }
    calculateGBest(bestParticle);
}

From source file:org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicyRaid.java

private DatanodeDescriptor chooseReplicaToDelete(Collection<LocatedBlock> companionBlocks,
        Collection<DatanodeDescriptor> dataNodes) throws IOException {

    if (dataNodes.isEmpty()) {
        return null;
    }/*  w  w  w  .  jav a2s.c  o m*/
    // Count the number of replicas on each node and rack
    final Map<String, Integer> nodeCompanionBlockCount = countCompanionBlocks(companionBlocks, false);
    final Map<String, Integer> rackCompanionBlockCount = countCompanionBlocks(companionBlocks, true);

    NodeComparator comparator = new NodeComparator(nodeCompanionBlockCount, rackCompanionBlockCount);
    return Collections.max(dataNodes, comparator);
}

From source file:pt.ist.fenixedu.tutorship.domain.Tutorship.java

private static Tutorship getLastTutorship(StudentCurricularPlan studentCurricularPlan) {
    if (!studentCurricularPlan.getTutorshipsSet().isEmpty()) {
        return Collections.max(studentCurricularPlan.getTutorshipsSet(),
                Tutorship.TUTORSHIP_START_DATE_COMPARATOR);
    }/*ww w .jav  a  2 s  .co m*/
    return null;
}

From source file:com.github.rvesse.github.pr.stats.PullRequestStats.java

public void run() throws IOException {
    if (help.showHelpIfRequested()) {
        CliCommandUsageGenerator generator = new CliCommandUsageGenerator();
        generator.usage(null, null, "pr-stats", this.metadata, this.parserConfig, System.out);
        return;/*  w  w  w. j av a  2s.  c om*/
    }

    GitHubClient client = new GitHubClient();
    prepareCredentials(client);
    client.setUserAgent("GitHub PR Stats Bot/0.1.0 (+http://github.com/rvesse/gh-pr-stats.git)");

    // Get the user just to force us to make one request so we can get stats
    // about the remaining requests
    @SuppressWarnings("unused")
    User user = new UserService(client).getUser();
    System.out.println("You have " + client.getRemainingRequests() + " GitHub API requests of "
            + client.getRequestLimit() + " remaining");
    long start = client.getRemainingRequests();

    // Collect statistics for the pull requests
    PullRequestService prService = new PullRequestService(client);
    RepositoryId repoId = prepareRepositoryId();
    List<PullRequest> prs = prService.getPullRequests(repoId, "all");
    PullRequestsCollector collector = new PullRequestsCollector(
            this.userSummary || this.userDetailedStats || this.all,
            this.mergeSummary || this.mergeDetailedStats || this.all);
    collector.start();
    for (PullRequest pr : prs) {
        System.out.println("Processing PR #" + pr.getNumber());
        collector.collect(client, pr);
    }
    collector.end();

    // Inform the user about how many API requests were used
    System.out.println();
    System.out.println("You have " + client.getRemainingRequests() + " GitHub API requests of "
            + client.getRequestLimit() + " remaining");
    System.out.println(
            "Generating statistics used " + (start - client.getRemainingRequests()) + " GitHub API requests");
    System.out.println();

    // Output Stats
    // Basic stats
    outputBasicStatus(collector);
    System.out.println();

    // Age Stats
    outputAgeStats(collector.getDaysToMergeStats(), "Days to Merge", true);
    System.out.println();
    outputAgeStats(collector.getDaysOpenStats(), "Days Open", true);
    System.out.println();
    outputAgeStats(collector.getDaysToCloseStats(), "Days to Close", true);
    System.out.println();

    // User Stats
    List<UserCollector> userStats = collector.getUserStats();
    UserComparator<UserCollector> userComparator = new UserComparator<UserCollector>();
    if (this.userSummary || this.all) {
        System.out.println("Total Users: " + userStats.size());

        if (userStats.size() > 0) {
            UserCollector maxUser = Collections.max(userStats, userComparator);
            List<UserCollector> maxUsers = findEquivalent(userStats, maxUser, userComparator);
            UserCollector minUser = Collections.min(userStats, userComparator);
            List<UserCollector> minUsers = findEquivalent(userStats, minUser, userComparator);

            System.out.println("Max Pull Requests by User: " + maxUser.getTotal() + " " + maxUsers);
            System.out.println("Min Pull Requests by User: " + minUser.getTotal() + " " + minUsers);
            System.out.println("Average Pull Requests per User: " + (collector.getTotal() / userStats.size()));
        }
        System.out.println();
    }

    if (userStats.size() > 0 && (this.userDetailedStats || this.all)) {
        Collections.sort(userStats, userComparator);
        for (AbstractUserPullRequestCollector userCollector : userStats) {
            outputUserStats(userCollector);
            System.out.println();
        }
    }

    // Merging User Stats
    List<MergingUserCollector> mergingUserStats = collector.getMergingUserStats();
    UserComparator<MergingUserCollector> mergeUserComparator = new UserComparator<MergingUserCollector>();
    if (this.mergeSummary || this.all) {
        System.out.println("Total Merging Users: " + mergingUserStats.size());

        if (mergingUserStats.size() > 0) {
            MergingUserCollector maxUser = Collections.max(mergingUserStats, mergeUserComparator);
            List<MergingUserCollector> maxUsers = findEquivalent(mergingUserStats, maxUser,
                    mergeUserComparator);
            MergingUserCollector minUser = Collections.min(mergingUserStats, mergeUserComparator);
            List<MergingUserCollector> minUsers = findEquivalent(mergingUserStats, minUser,
                    mergeUserComparator);

            System.out.println("Max Pull Requests Merged by User: " + maxUser.getMerged() + " " + maxUsers);
            System.out.println("Min Pull Requests Merged by User: " + minUser.getMerged() + " " + minUsers);
            System.out.println("Average Pull Requests Merged per User: "
                    + (collector.getMerged() / mergingUserStats.size()));
        }
        System.out.println();
    }

    if (mergingUserStats.size() > 0 && (this.mergeDetailedStats || this.all)) {
        Collections.sort(mergingUserStats, mergeUserComparator);
        for (MergingUserCollector userCollector : mergingUserStats) {
            outputUserStats(userCollector);
            System.out.println();
        }
    }

}

From source file:com.microblink.barcode.customcamera.camera2.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 w w w  .j  av a  2 s. c  o m
 * @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 maxWidth, int maxHeight, Size aspectRatio) {

    // Collect the supported resolutions that are at least as big as the preview Surface
    List<Size> bigEnough = 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) {
            bigEnough.add(option);
        }
    }

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

From source file:org.apache.hadoop.hdfs.server.namenode.BlockPlacementPolicyRaid.java

private DatanodeDescriptor chooseReplicaToDelete(Collection<LocatedBlock> companionBlocks,
        Collection<DatanodeDescriptor> dataNodes) throws IOException {

    if (dataNodes.isEmpty()) {
        return null;
    }//from  w w w.  ja va2 s . co  m
    // Count the number of replicas on each node and rack
    final Map<String, Integer>[] companionBlockCounts = countCompanionBlocks(companionBlocks);
    final Map<String, Integer> nodeCompanionBlockCount = companionBlockCounts[0];
    final Map<String, Integer> rackCompanionBlockCount = companionBlockCounts[1];

    NodeComparator comparator = new NodeComparator(nodeCompanionBlockCount, rackCompanionBlockCount);
    return Collections.max(dataNodes, comparator);
}

From source file:org.openvpms.web.workspace.customer.charge.PharmacyOrderPlacer.java

private PatientContext getPatientContext(Order order, PatientHistoryChanges changes) {
    PatientContext result = null;//from   w ww .  j a  va 2 s  .  c  o m
    List<Act> events = changes.getEvents(order.getPatient().getObjectReference());
    Act event;
    if (events == null || events.isEmpty()) {
        event = changes.getEvent(order.getEvent());
    } else {
        event = Collections.max(events, new Comparator<Act>() {
            @Override
            public int compare(Act o1, Act o2) {
                return DateRules.compareDateTime(o1.getActivityStartTime(), o2.getActivityStartTime(), true);
            }
        });
    }
    if (event != null) {
        result = factory.createContext(order.getPatient(), customer, event, location, order.getClinician());
    }
    return result;
}

From source file:dynamite.zafroshops.app.fragment.TypedZopsFragment.java

private void setZops(final boolean force) {
    Activity activity = getActivity();//from www . ja  v a  2s .  c om
    adapter = new TypedZopListViewAdapter(getActivity(), R.id.listViewItem, typedZops);
    final SharedPreferences preferences = activity.getPreferences(0);

    final SharedPreferences.Editor editor = preferences.edit();
    final ZopType type = (ZopType) getArguments().get(ARG_ZOP_TYPE);
    final String key = StorageKeys.ZOPS_KEY + type.toString();

    zopType = type;

    if (!preferences.contains(key)) {
        InputStream is = getResources().openRawResource(R.raw.zops);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        typedZops = new ArrayList<>(Collections2.filter(
                (ArrayList<MobileZop>) new Gson().fromJson(reader, new TypeToken<ArrayList<MobileZop>>() {
                }.getType()), new Predicate<MobileZop>() {
                    @Override
                    public boolean apply(MobileZop input) {
                        return input.Type == type && (!preferences.contains(StorageKeys.COUNTRY_KEY)
                                || preferences.getString(StorageKeys.COUNTRY_KEY, "").equals("")
                                || input.CountryID.equals(preferences.getString(StorageKeys.COUNTRY_KEY, "")));
                    }
                }));

        try {
            FileOutputStream fos = activity.openFileOutput(key, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            int count = typedZops.size();

            oos.writeObject(typedZops);
            oos.close();
            fos.close();
            editor.putString(key, Integer.toString(count));
            editor.commit();
            setCount(count);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    else if (preferences.contains(key)) {
        try {
            FileInputStream fis = activity.openFileInput(key);
            ObjectInputStream ois = new ObjectInputStream(fis);

            ArrayList<MobileZop> temp = (ArrayList) ois.readObject();
            typedZops = new ArrayList<>(Collections2.filter(temp, new Predicate<MobileZop>() {
                @Override
                public boolean apply(MobileZop input) {
                    return input.Type == type && (!preferences.contains(StorageKeys.COUNTRY_KEY)
                            || preferences.getString(StorageKeys.COUNTRY_KEY, "").equals("")
                            || input.CountryID.equals(preferences.getString(StorageKeys.COUNTRY_KEY, "")));
                }
            }));
            ois.close();
            fis.close();
            setCount(typedZops.size());
            if (adapter != null) {
                adapter.setObjects(typedZops);
                adapter.notifyDataSetChanged();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    if (force) {
        final ArrayList<Pair<String, String>> parameters;
        if (MainActivity.LastLocation != null) {
            parameters = new ArrayList<Pair<String, String>>() {
                {
                    add(new Pair<>("latitude", Double.toString(MainActivity.LastLocation.Latitude)));
                    add(new Pair<>("longitude", Double.toString(MainActivity.LastLocation.Longitude)));
                    add(new Pair<>("type", type.getText()));
                }
            };
        } else {
            parameters = new ArrayList<Pair<String, String>>() {
                {
                    add(new Pair<>("type", type.getText()));
                }
            };
        }

        ListenableFuture<JsonElement> result = MainActivity.MobileClient.invokeApi("mobileZop", "GET",
                parameters);

        Futures.addCallback(result, new FutureCallback<JsonElement>() {
            Activity activity = getActivity();

            @Override
            public void onSuccess(JsonElement result) {
                JsonArray typesAsJson = result.getAsJsonArray();
                if (typesAsJson != null) {
                    ArrayList<MobileZop> temp = new Gson().fromJson(result,
                            new TypeToken<ArrayList<MobileZop>>() {
                            }.getType());

                    int max = Collections.max(temp, new Comparator<MobileZop>() {
                        @Override
                        public int compare(MobileZop lhs, MobileZop rhs) {
                            if (lhs.DataVersion < rhs.DataVersion) {
                                return -1;
                            } else if (lhs.DataVersion > rhs.DataVersion) {
                                return 1;
                            } else {
                                return 0;
                            }
                        }
                    }).DataVersion;
                    ((MainActivity) activity).Versions.put(zopType, max);

                    try {
                        FileOutputStream fos = activity.openFileOutput(key, Context.MODE_PRIVATE);
                        ObjectOutputStream oos = new ObjectOutputStream(fos);
                        int count = typedZops.size();

                        typedZops = new ArrayList<>(Collections2.filter(temp, new Predicate<MobileZop>() {
                            @Override
                            public boolean apply(MobileZop input) {
                                return input.Type == type && (!preferences.contains(StorageKeys.COUNTRY_KEY)
                                        || preferences.getString(StorageKeys.COUNTRY_KEY, "").equals("")
                                        || input.CountryID
                                                .equals(preferences.getString(StorageKeys.COUNTRY_KEY, "")));
                            }
                        }));
                        oos.writeObject(typedZops);
                        oos.close();
                        fos.close();
                        editor.putString(key, Integer.toString(count));
                        editor.commit();
                        setCount(count);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (adapter != null) {
                    adapter.setObjects(typedZops);
                    resetVisibility(false);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(@NonNull Throwable t) {
                ListView zops = (ListView) activity.findViewById(R.id.listViewZops);
                RelativeLayout loader = (RelativeLayout) activity.findViewById(R.id.relativeLayoutLoader);
                LinearLayout noZops = (LinearLayout) activity.findViewById(R.id.noZops);

                resetVisibility(zops, noZops, loader, false);
            }
        });
    }
}