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

后端 未结 4 1916
我寻月下人不归
我寻月下人不归 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:38

    Generally, if you need an index, you’ll have to stream over the indices. Then, the task becomes straight-forward:

    List intArr = Arrays.asList(5, 8, 3, 2);
    IntStream.range(0, intArr.size())
      .reduce((a,b)->intArr.get(a)System.out.println("Index "+ix+", value "+intArr.get(ix)));
    

    a more elegant solution, which unfortunately incorporates boxing overhead is

    IntStream.range(0, intArr.size())
      .boxed().max(Comparator.comparing(intArr::get))
      .ifPresent(ix->System.out.println("Index "+ix+", value "+intArr.get(ix)));
    

提交回复
热议问题