2

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 ?

3 Answers 3

3

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()));
Sign up to request clarification or add additional context in comments.

6 Comments

Of course you have to handle the case when max is not present
but that would stream twice... interesting if it can be done with a single stream.
.intValue() is unnecessary. Java will auto-unbox.
Changing first line to int max = len.stream().mapToInt(Integer::intValue).max().orElse(0); would resolve issue raised by @grozandrei.
can use int max = Collections.max(len); function to get Max value
|
3

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]

1 Comment

pretty nice :) one plus
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.