Java streams | groupingby the same element

I have a stream of words that I want to sort according to the appearance of the same elements (= words)

For example: {Hello, world, hello}

to

Map<String,List<String>>

Hello}

World, {world}

What have I got so far:

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

Problem 1: the stream seems to have lost information about the string it is processing, so the compiler forces me to change the type to object, list

Question 2: I don't know what to put in the gastrointestinal tract and group them in the same way I know I can handle individual elements in a lambda expression, but I don't know how to get to the "outside" of each element to check for equality

thank you

Solution

The keyextractor you are searching for is the identity function:

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

Edit supplementary notes:

> Function. Identity () uses a method to return a 'function', which only returns the parameters it obtains. > Collectors. Groupingby (function < s, k > keyextractor) provides a collector that collects all elements of the stream to map < K, list < s > > It uses the keyextractor implementation to check the s class object of the stream and derive the key of type K from it This key is the key of the map, which is used to get (or create) the list in the result map to which the flow element is added

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>