Java中查找BigDecimal列表最小值索引的优化方法
{"title":"public static int getMinIndex(final Listjava\nfor (BigDecimal value : list) {\n if (value.compareTo(minValue) < 0) {\n minIndex = list.indexOf(value);\n minValue = value;\n }\n}\n\n\n2. 使用Java 8的Stream API:可以使用Stream API来处理列表,并使用min方法找到最小值。这样可以使代码更简洁和函数式。\n\njava\nOptional<BigDecimal> minValue = list.stream()\n .min(BigDecimal::compareTo);\nif (!minValue.isPresent()) {\n throw new IllegalArgumentException("List is empty");\n}\n\nreturn list.indexOf(minValue.get());\n\n\n注意:使用Stream API可能会对性能产生一些影响,因此需要权衡使用。\n\n3. 使用Java 8的IntStream和reduce方法:可以使用IntStream和reduce方法来找到最小值的索引。这样可以避免使用BigDecimal的compareTo方法,提高性能。\n\njava\nOptionalInt minIndex = IntStream.range(0, list.size())\n .reduce((a, b) -> list.get(a).compareTo(list.get(b)) < 0 ? a : b);\nif (!minIndex.isPresent()) {\n throw new IllegalArgumentException("List is empty");\n}\n\nreturn minIndex.getAsInt();\n\n\n注意:这种方法假设列表的大小不会超过Integer.MAX_VALUE。\n\n这些优化建议可以根据具体情况选择适合的方法。
原文地址: https://www.cveoy.top/t/topic/qaFh 著作权归作者所有。请勿转载和采集!