Java 8: find the index of the minimum value from the list
Say I have a list of elements (34,11,98,56,43)
Using the Java 8 stream, how do I find the index of the smallest element of the list (1 in this case)?
I know you can use list in Java Indexof (collections. Min (list)) is easily completed However, I'm looking at a solution like Scala. We can simply say list (34,43) zipWithIndex. min._ 2 to get the index of the minimum value
Is there anything that can use streams or lambda expressions (such as specific features of Java 8) to achieve the same results
Note: This is only for learning purposes I have no problems using the collections utility method
Solution
import static java.util.Comparator.comparingInt;
import static java.util.Comparator.comparingInt; int minIndex = IntStream.range(0,list.size()).@R_516_2419@ed() .min(comparingInt(list::get)) .get(); // or throw if empty list
As @ tagirvaleev mentioned in his answer, you can avoid boxing by using intstream #reduce instead of stream #min, but at the expense of concealing your intention:
int minIdx = IntStream.range(0,list.size()) .reduce((i,j) -> list.get(i) > list.get(j) ? j : i) .getAsInt(); // or throw