如何使用Java流API获取所有重复元素的索引
如何使用Java流API获取所有重复元素的索引?
例如,我们有:
List<Integer> input =
new ArrayList<>(Arrays.asList(312, 312, 195, 195, 195, 851, 335, 851, 99));
我可以将类似的元素分组:
result = input.stream().collect(Collectors.groupingBy(input::indexOf))
//result = {0=[312, 312], 2=[195, 195, 195], 5=[851, 851], 6=[335], 8=[99]}
但是我想得到这样的结果:
{312=[0, 1], 195=[2, 3, 4], 851=[5, 7]}
或者这样:
(0,1,2,3,4,5,7)
我该怎么做?
How can I get the indexes of all duplicate elements by using the Java stream API?
For example, we have:
List<Integer> input =
new ArrayList<>(Arrays.asList(312, 312, 195, 195, 195, 851, 335, 851, 99));
I could group same elements like this:
result = input.stream().collect(Collectors.groupingBy(input::indexOf))
//result = {0=[312, 312], 2=[195, 195, 195], 5=[851, 851], 6=[335], 8=[99]}
But I want get a result like this:
{312=[0, 1], 195=[2, 3, 4], 851=[5, 7]}
or just like this:
(0,1,2,3,4,5,7)
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
intstream
拥有所有值及其索引后,您可以简单地滤除具有超过1个值的条目。
完整示例:
You can Use
IntStream
Once you have all the values and their indexes you can simply filter out the entries which have more than 1 value.
Full example:
使用
collections.fquency
的另一种方法Another approach using
Collections.frequency
看起来仅通过循环就很容易解决。只需将
map
以输入值作为键,它是索引作为映射的值:输出
Looks like it's quite easy to solve by just for loop. Just keep a
Map
with input value as a key and it's index as a value of map:Output
您可以尝试以下代码 -
You can try below code -