Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I collect multiple maximum values from a List

Tags:

java

list

max

How to get max from an ArrayList that has more than one max? For example, if an ArrrayList contains max = 20 stored at index 2, 3 and 6, how do you get all that indicies?

like image 422
Ongchu Sherpa Avatar asked Mar 01 '26 20:03

Ongchu Sherpa


1 Answers

The obvious way is to first get maximum value by Collections.max(), then collect indicies where items are equal to max:

public <T extends Comparable<? super T>> List<Integer> maxIndicies(List<T> input) {
    if (input.isEmpty())  // avoid exception thrown by Collections.max() if input is empty
        return Collections.emptyList();
    final T max = Collections.max(input);
    return IntStream.range(0, input.size())
               .filter(i -> input.get(i).compareTo(max) == 0)
               .boxed()
               .collect(Collectors.toList()); 
}

Additionally, I'd like to propose another solution where iteration is performed only once. During iteration, you need to check two things for each item: 1) if it is greater than current max, set a new max and reset result list, 2) if it is equal to current max, add its index to result list:

public <T extends Comparable<? super T>> List<Integer> maxIndicies(List<T> input) {
    T max = null;
    List<Integer> res = new ArrayList<>();
    for (int i = 0; i < input.size(); i++) {
       T item = input.get(i);
       if (max == null || item.compareTo(max) > 0) {   // item > max => reset
           res.clear();
           max = item;
           res.add(i);
       } else if (item.compareTo(max) == 0)            // item equals current max
           res.add(i);
    }
    return res;
}

This won't give you value of max item itself, but you can get it by any returned index, simply as:

List<Integer> maxInd = maxIndicies(list);
maxValue = maxInd.isEmpty() ? null : list.get(maxInd.get(0));
like image 98
Alex Salauyou Avatar answered Mar 04 '26 10:03

Alex Salauyou