Priyank Jain
Priyank Jain

Reputation: 787

How to get index of multiple maximum value in List

In given list of Integers i want to find the multiple index of maximum value in List.

For example,

List<Integer> len=Arrays.asList(9,3,6,5,4,9);

Now i want to find the largest element which is 9 and its all index which are 0 and 5.

i have tried following code but it only gives me the first occurrence of element so from this code i am getting output only 0 not 5.

IntStream.range(0,len.size()).reduce((a, b) -> len.get(a) < len.get(b)?b:a).ifPresent(ix -> System.out.println("Index -"+ix));

So how can i achieve that ?

Upvotes: 2

Views: 1522

Answers (3)

Flown
Flown

Reputation: 11740

It is possible to use only one Stream pipeline:

List<Integer> len = Arrays.asList(9, 3, 6, 5, 4, 9);

List<Integer> indices = IntStream.range(0, len.size()).boxed()
    .collect(Collectors.collectingAndThen(
        Collectors.groupingBy(len::get, TreeMap::new, Collectors.toList()),
        m -> m.isEmpty() ? Collections.emptyList() : m.lastEntry().getValue()));
System.out.println(indices);

First group your indices to the respective values in your list. Then you have to decide what to do if the intermediate map is empty. Either you throw an NoSuchElementException or return an empty list. In my example I chose the latter case.


Result:

[0, 5]

Upvotes: 3

Markus Benko
Markus Benko

Reputation: 1507

If the result doesn't have to be a Stream or Optional you could accomplish the task using this code:

IntStream.range(0, len.size()).boxed()
    .sorted(Comparator.comparing((Integer i) -> len.get(i)).reversed())
    .reduce(-1, (ixMax, ix) -> {
        if (ixMax == -1 || len.get(ixMax) == len.get(ix)) {
            System.out.println("Index -" + ix);
            return ix;
        } else {
            return ixMax;
        }
    });

Although answering the question it's probably neither concise nor very performant to be honest. With some work it should be possible to replace the if-else block with code making use of Optional.

Upvotes: 1

Andrei G
Andrei G

Reputation: 670

Something like this:

int max = len.stream().max(Integer::compareTo).get();
System.out.println(IntStream.range(0, len.size()).filter(ix -> len.get(ix).intValue() == max).boxed()
            .collect(Collectors.toList()));

Upvotes: 3

Related Questions