Java 8: Find index of minimum value from a List

前端 未结 4 1718
北荒
北荒 2021-02-01 23:50

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)

4条回答
  •  [愿得一人]
    2021-02-02 00:21

    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
    

提交回复
热议问题