是否有一些仅流的方法来确定最大流元素的索引? [英] Is There Some Stream-Only Way To Determine The Index Of The Max Stream Element?
问题描述
我有一个 Stream< Set< Integer>> intSetStream
。
我可以这样做...
Set<Integer> theSetWithTheMax = intSetStream.max( (x,y)->{ return Integer.compare( x.size(), y.size() ); } ).get( );
...我得到了 Set< Integer>
其中包含 Integer
元素的数量最多。
...and I get a hold of the Set<Integer>
that has the highest number of Integer
elements in it.
这很棒。但我真正需要知道的是,这是流
中的第一个 Set
这是最大值?或者它是 Stream
中的第10个 Set
?或 i
th 设置
?其中哪一个元素最多?
That's great. But what I really need to know is, is it the 1st Set
in that Stream
that's the max? Or is it the 10th Set
in the Stream
? Or the i
th Set
? Which one of them has the most elements in it?
所以我的问题是:有没有办法 - 使用Stream API - 我可以在 Stream $中确定
i
设置
对于 Set.size()
调用,c $ c> of Set
s返回所有值的最大值?
So my question is: Is there some way — using the Stream API — that I can determine "It was the i
th Set
in the Stream
of Set
s that returned the largest value of them all, for the Set.size( )
call"?
我能想到的最佳解决方案是迭代 Stream< Set< Integer>>
(使用 intSetStream.iterator()
)并进行手动滚动的 max()
计算。但我希望能够学习更多 Stream
-y方式来实现它;如果有这样的话。
The best solution I can think of, is to iterate over the Stream<Set<Integer>>
(using intSetStream.iterator()
) and do a hand-rolled max( )
calculation. But I'm hoping to learn a more Stream
-y way to go about it; if there is such a thing.
推荐答案
一种方法是首先映射 Stream< Set< ;整数>>
到集合<整数>
其中每个元素的大小是每个 Set< Integer>
然后你可以提取给出 Stream< Set< Integer>>
的最大元素数量,然后得到这个集合的索引通过查找大小集合中最大数字的索引。
One way to do it is to firstly map Stream<Set<Integer>>
to a Collection<Integer>
where each element is the size of each Set<Integer>
and then you can extract what is the largest number of elements given Stream<Set<Integer>>
and then get the "index" of this set by finding an index of the largest number in the collection of sizes.
请考虑以下示例:
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class IntSetStreamExample {
public static void main(String[] args) {
final Stream<Set<Integer>> stream = Stream.of(
new HashSet<>(Arrays.asList(1,2,3)),
new HashSet<>(Arrays.asList(1,2)),
new HashSet<>(Arrays.asList(1,2,3,4,5)),
new HashSet<>(Arrays.asList(0)),
new HashSet<>(Arrays.asList(0,1,2,3,4,5)),
new HashSet<>()
);
final List<Integer> result = stream.map(Set::size).collect(Collectors.toList());
System.out.println("List of number of elements in Stream<Set<Integer>>: " + result);
final int max = Collections.max(result);
System.out.println("Largest set contains " + max + " elements");
final int index = result.indexOf(max);
System.out.println("Index of the largest set: " + index);
}
}
示例输出可能如下所示:
The exemplary output may look like this:
List of number of elements in Stream<Set<Integer>>: [3, 2, 5, 1, 6, 0]
Largest set contains 6 elements
Index of the largest set: 4
这篇关于是否有一些仅流的方法来确定最大流元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!