当两个值与最大值并列时,如何在 ArrayList 中返回最大值?



到目前为止,我有这个方法,它应该找到ArrayList的最大年龄。但是,在我的数据中,我有两个值,对于关节最大值,它们并列在 58。如何从此循环中获得第二个 58?前 58 个的索引是 1,但我需要的索引是 4。我无法硬编码。

public static int maxAge (ArrayList<Integer> ages) {
int hold = 0;
int max = 0;
for (int i = 0; i < ages.size(); i++) {
if (max < ages.get(i)) {
max = ages.get(i);
hold = i;
}
else i++;       
}
return hold;
}

您只需将条件更改为:

if (max <= ages.get(i))

这取决于你为什么想要其他 58 个。如果要返回最新的匹配项,可以向后循环。

我知道,很丑陋。但我会尝试编写一个功能版本。

Optional<Integer> max = ages.stream()
.max(Integer::compare);
if (max.isPresent()) {
return IntStream.range(0, ages.size())
.mapToObj(pos -> {
return new int[] {pos, ages.get(pos)};
})
.filter(pair -> pair[1] == max.get())
.collect(Collectors.toCollection(LinkedList::new))
.getLast()[0];
} else
return 0;

有多种方法可以更改条件以适合您的描述。试试这个:

public static int maxAge (ArrayList<Integer> ages) {
int hold = 0;
int max = 0;
for (int i = 0; i < ages.size(); i++) {
if (max < ages.get(i) || max == ages.get(i) {
max = ages.get(i);
hold = i;
}
else i++;       
}
return hold;
}

下面的代码将使您能够返回与列表最大值关联的所有索引。但是你必须在Java 8上运行它,因为它使用Lambda表达式。

public static ArrayList<Integer> maxAge (ArrayList<Integer> ages ) {
int max = 0;
ArrayList<Integer> maxIndexes = new ArrayList<Integer>() ;
for (int i = 0; i < ages.size(); i++) {
if (max <= ages.get(i)) {
final int finalMax = max ;
final int finalIndex = i ;
maxIndexes.removeIf((elt)-> finalMax < ages.get(finalIndex)) ;
maxIndexes.add(i) ;
max = ages.get(i) ;
}               
}
return maxIndexes ;
}

最新更新