Java 8:从List中查找最小值索引 [英] Java 8: Find index of minimum value from a List

查看:984
本文介绍了Java 8:从List中查找最小值索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含元素的列表(34,11,98,56,43)

Say I have a list with elements (34, 11, 98, 56, 43).

使用Java 8流,如何找到列表中最小元素的索引(例如在这种情况下为1)?

Using Java 8 streams, how do I find the index of the minimum element of the list (e.g. 1 in this case)?

我知道这可以在Java中轻松完成使用 list.indexOf(Collections.min(list))。但是,我正在寻找类似Scala的解决方案,我们可以简单地说 List(34,11,98,56,43).zipWithIndex.min._2 来获取索引最小值。

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.

是否可以使用流或lambda表达式(比如Java 8特定功能)来实现相同的结果。

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

正如@TagirValeev在这个答案,您可以使用 IntStream #reduce 代替 Stream#来避免装箱min ,但是以掩盖意图为代价:

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

这篇关于Java 8:从List中查找最小值索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆