java - 查找数组中的最高值,但是如果最高值在数组中存在两个或多个位置怎么办?

标签 java

在我的程序中,我有一个数组,我必须找出数组中的哪个位置具有最高值。唯一的问题是,如果数组中的两个或多个位置存在最高值怎么办?

这些是找到最高值的方法,但如果最高值在另外两个地方相同,它们就不起作用了?

for (int counter = 1; counter < decMax.length; counter++)
{
     if (decMax[counter] > max)
     {
      max = decMax[counter];
     }
}

System.out.println("The highest maximum for the December is: " + max);




public int maxValue(int array[]){
  List<Integer> list = new ArrayList<Integer>();
  for (int i = 0; i < array.length; i++) {
    list.add(array[i]);
  }
 return Collections.max(list);
}




public int maxValue(int array[]){
  int max = Arrays.stream(array).max().getAsInt();
  return max;
}

最佳答案

您可以返回 List<Integer>具有找到最大值的位置/索引。

当您找到max时用它来查找它在数组中存在的索引:

public List<Integer> maxValue(int array[]){
        int max = Arrays.stream(array).max().orElse(-1);
        return IntStream.range(0, array.length)
                        .filter(idx -> array[idx] == max)
                        .mapToObj(i -> i)
                        .collect(Collectors.toList());
}

关于java - 查找数组中的最高值,但是如果最高值在数组中存在两个或多个位置怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57904515/

相关文章:

java - Jsoup HTML 解析 - 复杂节点 [Java]

java - 纯 java sqlite 库?

java - 我们如何在数组列表中添加(long,String)?

java - 如何在 Azure 的 Spring Cloud Functions 中 Autowiring 我的 Bean?

java - 在 C++ 中有类似的东西吗

java - Eclipse/STS 自动将 "new"更正为 "newEmail"

java - 如何在 java/hibernate/mysql 中连接 2 个或更多表?

java - 封闭系统和开放系统签名有什么区别?

java - 在 Hibernate 中对属性使用惰性

java - 在 java 中列出 ubuntu 上的附加设备