如何一次性获取数组的索引和最大值? [英] How to get the index and max value of an array in one shot?

查看:332
本文介绍了如何一次性获取数组的索引和最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个整数元素列表,如何一次性获取最大值及其索引。如果有多个元素具有相同的最大值,则返回任何一个元素的索引就可以了。

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 them is fine.

例如:

// Initialize list of integer
List<Integer> intList = Arrays.asList(5, 8, 3, 2);
// To get max value
Optional<Integer> maxVal = intList.stream().reduce(Integer::max);
// But how could I also get its index without iterating the array again?

如果我只需要做一次,我可以对数组进行排序并得到第一个或最后一个一个(基于排序顺序)。但是,我想看看我们如何在没有排序的情况下做到这一点。

If I have to do it only once, I could just sort the array and get the first or last one (based on sort order). However, I would like to see how we can do it without sorting.

推荐答案

一般来说,如果你需要一个索引,你'我必须流过指数。然后,任务变得直截了当:

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

List<Integer> intArr = Arrays.asList(5, 8, 3, 2);
IntStream.range(0, intArr.size())
  .reduce((a,b)->intArr.get(a)<intArr.get(b)? b: a)
  .ifPresent(ix->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)));

这篇关于如何一次性获取数组的索引和最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆