Java 8: Find index of minimum value from a List

前端 未结 4 1719
北荒
北荒 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:20

    Here's two possible solutions using my StreamEx library:

    int idx = IntStreamEx.ofIndices(list).minBy(list::get).getAsInt();
    

    Or:

    int idx = EntryStream.of(list).minBy(Entry::getValue).get().getKey();
    

    The second solution internally is very close to one proposed by @AlexisC. The first one is probably the fastest as it does not use boxing (internally it's a reduce operation).

    Without using third-party code @Misha's answer looks the best for me.

提交回复
热议问题