Java Streams | groupingBy相同的元素 [英] Java Streams | groupingBy same elements

查看:219
本文介绍了Java Streams | groupingBy相同的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单词流,我想根据相同元素(=单词)的出现对它们进行排序。

I have a stream of words and I would like to sort them according to the occurrence of same elements (=words).

例如:{hello,world,你好}

e.g.: {hello, world, hello}

Map<String, List<String>>

hello,{hello,hello}

hello, {hello, hello}

world,{world}

world, {world}

到目前为止我所拥有的:

What i have so far:

Map<Object, List<String>> list = streamofWords.collect(Collectors.groupingBy(???));

问题1:流似乎丢失了他正在处理字符串的信息,因此编译器强迫我将类型更改为对象,列表

Problem 1: The stream seems to lose the information that he is processing Strings, therefore the compiler forces me to change the type to Object, List

问题2:我不知道在胃肠道内放置什么以将其分组。我知道我能够处理lambda表达式中的单个元素,但我不知道如何到达每个元素的外部以检查是否相等。

Problem 2: I don't know what to put inside the parentesis to group it by the same occurrence. I know that I am able to process single elements within th lambda-expression but I have no idea how to reach "outside" each element to check for equality.

谢谢

推荐答案

您要搜索的KeyExtractor是身份功能:

The KeyExtractor you are searching for is the identity function:

Map<String, List<String>> list = streamofWords.collect(Collectors.groupingBy(Function.identity()));

编辑补充说明:


  • Function.identity()使用一个方法返回一个'Function',只返回它得到的参数。

  • Collectors.groupingBy(函数< S,K> keyExtractor)提供了一个收集器,它将流的所有元素收集到 Map< K ,列出< S>> 。它使用keyExtractor实现来检查流的 S 类型的对象,并从中推导出类型为 K 的键。他们。此键是地图的键,用于获取(或创建)添加了流元素的结果映射中的列表。

  • Function.identity() retuns a 'Function' with one method that does nothing more than returning the argument it gets.
  • Collectors.groupingBy(Function<S, K> keyExtractor) provides a collector, which collects all elements of the stream to a Map<K, List<S>>. It is using the keyExtractor implementation it gets to inspect the stream's objects of type S and deduce a key of type K from them. This key is the map's key used to get (or create) the list in the result map the stream element is added to.

这篇关于Java Streams | groupingBy相同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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