博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Collect from stream into a multimap

Posted on 2020-08-07 14:41  和风细雨汪汪  阅读(235)  评论(0编辑  收藏  举报

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]}