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)?
I know this can be done easily in Java using list.indexOf(Collections.min(list)). However, I am looking at a Scala like solution where we can simply say List(34, 11, 98, 56, 43).zipWithIndex.min._2 to get the index of minimum value.
Is there anything that can be done using streams or lambda expressions (say Java 8 specific features) to achieve the same result.
Note: This is just for learning purpose. I don't have any problem in using Collections utility methods.
解决方案
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