简体   繁体   中英

Merge function for two lists in java 8

If I have a string how do I create Map<Character, List<Integer>> that maps what index each character occurs at using streams. This is what I currently have and it works is there a more elegant way to do this?

    Map<Character, List<Integer>> occurs = IntStream.range(0, str.length())
    .boxed()
    .collect(toMap(str::charAt , Arrays::asList, (v1, v2) -> {
        List<Integer> list = new ArrayList<>();
        list.addAll(v1);
        list.addAll(v2);
        return list;
    }));

You don't need to implement this behavior yourself - just use the built-in Collectors#groupingBy :

Map<Character, List<Integer>> occurs =
    IntStream.range(0, str.length())
             .boxed()
             .collect(Collectors.groupingBy(str::charAt));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM