gpt4 book ai didi

java - 在Java中查找ArrayList中两个索引之间的最大值

转载 作者:行者123 更新时间:2023-11-30 05:22:20 25 4
gpt4 key购买 nike

我试图找到 ArrayList 中两个索引之间的最高值。我对编码非常陌生并且陷入困境。我已经编写了一个方法来查找整个 ArrayList 的最高值,但是当我尝试编写在 ArrayList 的两个索引之间查找并找到最高值的方法时,我得到的只是整个数组列表的最高值。

这是找到整个 ArrayList 的最高值的方法:

public int findMaxReadingIndex() {
int maxValue = (int) sensorReadings.get(0).getValue();
int maxIndex = 0;
int i = 0;

for (SensorReading sensorReading : sensorReadings) {
if (sensorReading.getValue() > maxValue) {
maxValue = (int) sensorReading.getValue();
maxIndex = i;
}

i++;
}

return maxIndex;
}

这是应该找到 startIndex 和 endIndex 之间的最高值的方法。在本例中,我希望 startIndex 为 5,endIndex 为 13:

...

public int findMaxReadingIndex1(int startIndex, int endIndex) {
startIndex = (int) sensorReadings.get(5).getValue();
endIndex = (int) sensorReadings.get(13).getValue();
int maxValIndex = 0;

for (SensorReading sensorReading : sensorReadings) {
if (startIndex < sensorReadings.size() && sensorReadings.size() < endIndex) {

maxValIndex = findMaxReadingIndex();
}
}

return maxValIndex;
}

...

感谢任何帮助!

最佳答案

tl;博士

IntStream                                               // Handy utility method for producing a stream of integers.
.range( 100 , 120 ) // Generate a stream from 100 to 119. Half-open approach means we go up to, but do not include, the limit of 120.
.boxed() // Convert an `IntStream` to a `Stream<Integer>`.
.collect( Collectors.toList() ) // Collect the elements from this stream, feeding them into a newly instantiated `List`.
.subList( 5 , 13 ) // Return a `List` of a subset of elements from the first list.
.stream() // Produce a `Stream` of the elements in that `List`.
.max( Comparator.comparingInt( Integer :: intValue ) ) // Compare each element as an `int`. Perhaps there is a better way to do this comparison, to avoid auto-boxing from object to primitive.
.get() // Extract a value from an `Optional`.

112

让我们通过使用流来体验一下。

首先,我们需要一系列Integer我们的演示的对象。

我们可以循环填充这样的 List .

List < Integer > numbers = new ArrayList <>( 20 );
for ( int i = 100 ; i < 120 ; i++ )
{
numbers.add( i );
}

或者也可以在这部分使用流,就像墙一样寻找最大值。

List < Integer > numbers = 
IntStream
.range( 100 , 120 )
.boxed()
.collect( Collectors.toList() )
;

numbers = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119]

使用 Stream::max 查找最大值。

接下来我们使用List::subList从列表中获取所需的元素子集。然后我们创建该子列表的流。流中的每个元素都通过 max 馈送其中将整数值作为测试进行比较。调用Optional::get返回找到的最大值。 .

Integer biggest = 
numbers
.subList( 5 , 13 )
.stream()
.max( Comparator.comparingInt( Integer :: intValue ) )
.get()
;

biggest = 112

关于java - 在Java中查找ArrayList中两个索引之间的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59341019/

25 4 0