How to get the index and max value of an array in one shot?

后端 未结 4 1918
我寻月下人不归
我寻月下人不归 2020-12-05 15:58

Given a list of integer elements, how to get the max value and it\'s index in one shot. If there is more than one element with same max value, returning index of any one of

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 16:45

    If you don't mind using third-party code, my StreamEx library provides some shortcuts for this task:

    List intArr = Arrays.asList(5, 8, 3, 2);
    IntStreamEx.ofIndices(intArr)
               .maxBy(intArr::get)
               .ifPresent(ix->System.out.println("Index "+ix+", value "+intArr.get(ix)));
    

    Internally it's close to the first solution provided by @Holger (no boxing).

提交回复
热议问题