Java 8: Find index of minimum value from a List

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

    You could do it like this:

    int indexMin = IntStream.range(0, list.size())
                    .mapToObj(i -> new SimpleEntry<>(i, list.get(i)))
                    .min(comparingInt(SimpleEntry::getValue))
                    .map(SimpleEntry::getKey)
                    .orElse(-1);
    

    If the list is a random access list, get is a constant time operation. The API lacks of a standard tuple class, so I used the SimpleEntry from the AbstractMap class as a substitute.

    So IntStream.range generates a stream of indexes from the list from which you map each index to its corresponding value. Then you get the minimum element by providing a comparator on the values (the ones in the list). From there you map the Optional> to an Optional from which you get the index (or -1 if the optional is empty).

    As an aside, I would probably use a simple for-loop to get the index of the minimum value, as your combination of min / indexOf does 2 passes over the list.

    You might also be interested to check Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)

提交回复
热议问题