Java 中获取列表中第一个最小值的索引,处理多个最小值的情况
如果有多个最小值,你可以使用"IntStream.range"方法来获取第一个最小值的索引。代码示例如下:\n\njava\nOptional<BigDecimal> minValue = list.stream()\n .min(BigDecimal::compareTo);\nif (!minValue.isPresent()) {\n throw new IllegalArgumentException("List is empty");\n}\n\nBigDecimal min = minValue.get();\nint index = IntStream.range(0, list.size())\n .filter(i -> list.get(i).equals(min))\n .findFirst()\n .orElse(-1);\n\nif (index == -1) {\n throw new IllegalArgumentException("List does not contain the minimum value");\n}\n\nreturn index;\n\n\n这里通过使用"IntStream.range"方法创建一个整数流,然后使用"filter"方法过滤出与最小值相等的元素的索引,再使用"findFirst"方法获取第一个符合条件的索引。如果找不到符合条件的索引,则返回-1。
原文地址: https://www.cveoy.top/t/topic/qaGv 著作权归作者所有。请勿转载和采集!