【问题标题】:How to find the max value of an Arraylist and two of its Index position using Java如何使用 Java 找到 Arraylist 的最大值及其两个索引位置
【发布时间】:2012-05-13 08:04:45
【问题描述】:

如何从Arraylist 及其索引位置中找到最大值?

ArrayList ar = new ArrayList();
ar.add(2); // position 0
ar.add(4); // position 1
ar.add(12); // position 2
ar.add(10); // position 3
ar.add(12); // position 4

String obj = Collections.max(ar);
int index = ar.indexOf(obj);

System.out.println("obj max value is " + obj + " and index position is " + index);

上述程序只是将输出作为第一个最大对象返回,其值为12,索引位置为2

但我的实际输出应该是索引位置24(因为最大值12 存在于两个索引位置)。

【问题讨论】:

  • 到目前为止你尝试过什么?请阅读FAQHow to Ask。此外,您已经提出了 13 个问题并接受了零回答。请返回并接受一些答案。
  • 为什么不简单地使用for 循环来遍历列表,使用.get(i) 获取每个列表元素。

标签: java arraylist


【解决方案1】:

您可以使用 Collections 查找列表的最大值,然后使用属性 indexOf 查找其在列表中的位置。

List<Integer> myList = new ArrayList<Integer>();
myList.add(3); // adding some values
myList.add(5);
myList.add(7);
myList.add(3);
myList.add(1);

Integer maxVal = Collections.max(myList); // should return 7
Integer maxIdx = myList.indexOf(maxVal); // should return 2 (position of the value 7)

【讨论】:

    【解决方案2】:

    从 Java 8 开始,这可以通过以下方式完成:

    int index = IntStream.range(0, ar.size()).boxed()
            .max(Comparator.comparing(ar::get)).orElse(-1);
    

    【讨论】:

    • 这是最酷的答案!你能解释一下你的解决方案吗?
    • @likejudo,这个想法很简单:我获取给定ArrayList (IntStream.range(0, ar.size())) 的所有索引,然后将它们装箱(获取Stream&lt;Integer)以便能够使用比较器,然后取最大索引不是比较自己,而是从给定的ArrayList 中获取元素。 max的结果是Optional,这样在空输入的情况下,我会得到Optional.empty()的结果。在这种情况下,我会返回-1
    【解决方案3】:

    未经测试:

    public static int maxIndex(List<Integer> list) {
      Integer i=0, maxIndex=-1, max=null;
      for (Integer x : list) {
        if ((x!=null) && ((max==null) || (x>max))) {
          max = x;
          maxIndex = i;
        }
        i++;
      }
      return maxIndex
    }
    // ...
    maxIndex(Arrays.asList(1, 2, 3, 2, 1)); // => 2
    maxIndex(Arrays.asList(null, null)); // => -1
    maxIndex(new ArrayList<Integer>()); // => -1
    

    【讨论】:

      【解决方案4】:

      只需遍历一次列表,有另一个列表来推送最大数量的索引

      【讨论】:

        【解决方案5】:

        public static void main(String[] args){

            List<Integer> ar=new ArrayList<Integer>();
            ar.add(2); `adding the values in the list`
            ar.add(5);
            ar.add(6);
            ar.add(4);
            ar.add(6);
            ar.add(5);
            ar.add(6);
        
            int max=Collections.max(ar);
        
            while(ar.contains(max))
            {
                int i=ar.indexOf(max); 
                System.out.println("the index of 6:"+ar.indexOf(max));
                ar.set(i, -1);
                System.out.println(ar);
            }       
        

        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-28
          • 2016-02-24
          • 2016-01-04
          • 1970-01-01
          • 1970-01-01
          • 2017-09-23
          • 2023-03-26
          相关资源
          最近更新 更多