How to find all occurences of the highest number in a list?

Viewed 114

Basically, if I have an ArrayList<Integer> containing <0, 1, 5, 5, 4, 2>, I need to create a separate ArrayList of <2, 3> for the indexes.

I understand how to get the index for the first appearance of the largest number, but I don't know how to get all of them at the same time.

I was originally thinking:

int highest = 0;

for (int b = 0; b < arrlst.size(); b++) {
    int p = arrlst.get(b);

    if (highest <= p) {
        highest = p;
        highestindex.add(b);
    }
}

But then I realised that would automatically add the first one, as well as any that were higher than the current max, even if they were not the overall max.

I then thought of putting the highestindex.add(...) part outside the loop but then it would only add the last index and not all of them.

4 Answers

I'd go for adding to and clearing a List<Integer>:

public ArrayList<Integer> getIndexesOfHighestNum(List<Integer> list) {
    List<Integer> indexes = new ArrayList<Integer>();
    int highest = Integer.MIN_VALUE;

    for (int i = 0; i < list.size(); i++) {
        int value = list.get(i);

        if (value > highest) {
            indexes.clear();
            indexes.add(i);
            highest = value;
        } else if (value == highest)
            indexes.add(i);
    }

    return indexes;
}

You can do it with stream as,

int max = intArr.stream().reduce(Integer::max).get();
IntStream.range(0, intArr.size()).boxed()
        .filter(i -> max == intArr.get(i))
        .collect(Collectors.toList());

You can first get the max number and then save the indices of the elements having this value as follows:

private static List<Integer> getMaxIndices(int[] list){
        int max = list[0];
        for(int i = 1; i < list.length; i++)
            if(max < list[i])
                max = list[i];
        List<Integer> res = new ArrayList<>();
        for(int i = 0; i < list.length; i++)
            if(list[i] == max)
                res.add(i);
        return res;
}

To simplify the code, we can make use of Collections#max to get the maximum value.
To better express our intention(filter index with maximum value), we can use IntStream instead of a for loop.

public static List<Integer> getMultipleMaxIndex(final List<Integer> from) {
    if (from.isEmpty()) {
        return Collections.emptyList();
    }
    final Integer max = Collections.max(from);
    IntStream indexes = IntStream.range(0, from.size() - 1);
    return indexes.filter(index -> from.get(index).equals(max)).boxed().collect(Collectors.toList());
}
Related