Say I have a list with elements (34, 11, 98, 56, 43)
.
Using Java 8 streams, how do I find the index of the minimum element of the list (e.g. 1 in this case)
import static java.util.Comparator.comparingInt;
int minIndex = IntStream.range(0,list.size()).boxed()
.min(comparingInt(list::get))
.get(); // or throw if empty list
As @TagirValeev mentions in his answer, you can avoid boxing by using IntStream#reduce
instead of Stream#min
, but at the cost of obscuring the intent:
int minIdx = IntStream.range(0,list.size())
.reduce((i,j) -> list.get(i) > list.get(j) ? j : i)
.getAsInt(); // or throw