Java 中获取 List 中多个最小值的索引
如果 List 中有多个最小值,使用 list.indexOf(minValue.get()) 方法无法获取所有最小值的索引。可以使用 filter 方法来过滤出所有最小值的索引。
以下是一个示例代码:
Optional<BigDecimal> minValue = list.stream()
.min(BigDecimal::compareTo);
if (!minValue.isPresent()) {
throw new IllegalArgumentException('List is empty');
}
BigDecimal min = minValue.get();
List<Integer> minIndices = IntStream.range(0, list.size())
.filter(i -> list.get(i).equals(min))
.boxed()
.collect(Collectors.toList());
return minIndices;
在上述代码中,我们首先找到最小值 (minValue),然后使用 IntStream.range 方法生成一个包含所有索引的流。接下来,我们使用 filter 方法来过滤出所有值等于最小值的索引。最后,我们将过滤后的索引收集到一个列表 (minIndices) 中并返回。
原文地址: https://www.cveoy.top/t/topic/qaGu 著作权归作者所有。请勿转载和采集!