Java Stream 获取列表中最小值索引:处理多个最小值情况
如果有多个最小值,可以使用filter方法来过滤出所有最小值的索引。以下是一个示例代码:
Optional<BigDecimal> minValue = list.stream()
.min(BigDecimal::compareTo);
if (!minValue.isPresent()) {
throw new IllegalArgumentException("List is empty");
}
List<Integer> minIndexes = IntStream.range(0, list.size())
.filter(i -> list.get(i).equals(minValue.get()))
.boxed()
.collect(Collectors.toList());
return minIndexes;
这段代码将返回一个List<Integer>,其中包含了所有最小值的索引。如果只需要返回第一个最小值的索引,可以使用minIndexes.get(0)来获取。
原文地址: https://www.cveoy.top/t/topic/qaF9 著作权归作者所有。请勿转载和采集!