Collect from stream into a multimap

Jeeppp :

I have a phrase and I'm splitting on white space and creating a map that would hold the word and the index position of the word.

I worked fine. But the problem is when the phrases contained duplicate words. So I wanted to use com.google.common.collect.Multimap.

Is there a way to generate the Multimap using the below stream's collector?

List<String> words = new ArrayList<>(Arrays.asList(phrase.split("\\s+")));
Map<String, Integer> tokenMap = IntStream.range(0, words.size())
            .boxed()
            .collect(Collectors.toMap(words::get, i -> i));
Samuel Philipp :

You can just use this:

List<String> words = Arrays.asList("a b c d e a b c".split("\\s+"));
Multimap<String, Integer> tokenMap = IntStream.range(0, words.size()).boxed()
        .collect(ArrayListMultimap::create, (m, i) -> m.put(words.get(i), i), Multimap::putAll);

The result will be:

{a=[0, 5], b=[1, 6], c=[2, 7], d=[3], e=[4]}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166503&siteId=1