[英]Finding all the indexes that contain max value
I have a list of lists in Java. 我有一个Java清单清单。 It is supposed to get the last item of each list and place it in another list named
lastItems
, then it will get the max value of lastItems
and its index. 应该获取每个列表的最后一项并将其放置在另一个名为
lastItems
列表中,然后它将获取lastItems
及其索引的最大值。 Here is the code: 这是代码:
List<List<Integer>> myList = new ArrayList<>();
myList.add(new ArrayList<Integer>());
myList.add(new ArrayList<Integer>());
myList.add(new ArrayList<Integer>());
myList.get(0).add(1);
myList.get(0).add(2);
myList.get(0).add(3);
myList.get(1).add(4);
myList.get(1).add(5);
myList.get(1).add(6);
myList.get(2).add(7);
myList.get(2).add(8);
myList.get(2).add(9);
if (!myList.contains(Collections.EMPTY_LIST) && !myList.contains(null) && myList.stream().allMatch(l -> l.size() == L.get(0).size())) {
int[] lastItems = myList.stream().mapToInt(x -> x.get(x.size() - 1)).toArray();
int maxValue = Arrays.stream(lastItems).max().getAsInt();
int index = IntStream.range(0, lastItems.length).filter(i -> maxValue == lastItems[i]).findFirst().orElse(-1));
System.out.println(maxValue);
}
but the problem is that IntStream.range(0, lastItems.length).filter(i -> maxValue == lastItems[i]).findFirst().orElse(-1))
finds only the index of the first maxValue
in the list, but I want to find all the indexes that may contain maxValue
(for example in list = [9, 5, 9]
, index = 0 and index=2 contain the maxValue
). 但问题是
IntStream.range(0, lastItems.length).filter(i -> maxValue == lastItems[i]).findFirst().orElse(-1))
仅在第一个maxValue
的索引中找到列表,但我想查找所有可能包含maxValue
的索引(例如,在list = [9, 5, 9]
maxValue
list = [9, 5, 9]
,索引= 0和index = 2包含maxValue
)。 How can I do this? 我怎样才能做到这一点?
Why not just keep it simple? 为什么不保持简单呢? After finding the
maxValue
, use a simple for-loop to find out the index of the largest values. 找到
maxValue
,使用简单的for循环找出最大值的索引。
int[] lastItems = myList.stream().mapToInt(x -> x.get(x.size() - 1)).toArray();
int maxValue = Arrays.stream(lastItems).max().getAsInt();
for (int i = 0; i < lastItems.length; i++) {
if (maxValue == lastItems[i])
System.out.println("MAx value = " + lastItems[i] + " with index " + i);
}
You may do it like so, 你可以这样做
int[] maxIndices = IntStream.range(0, lastItems.length)
.filter(i -> lastItems[i] == maxValue)
.toArray();
There's no point of using findFirst
if you want to get the indices of all of the max values. 如果要获取所有最大值的索引,则没有必要使用
findFirst
。 Just collect the matching values into a container instead. 只需将匹配的值收集到容器中即可。
If you just want to print it, then it would be, 如果您只想打印它,那就可以了,
IntStream.range(0, lastItems.length)
.filter(i -> lastItems[i] == maxValue)
.forEach(System.out::println);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.