How to do a one to many mapping by using Java lambdas and streams?

torty torty :

I want to split a list of numbers into multiples of 2, 3, 5 and store the result in a Map. Sample output will be like :

2 -> 2, 6, 10, 18 etc.
3 -> 3, 6, 9 etc.
5 -> 5, 10 etc.

I tried different ways of grouping (by using Collectors.groupingBy()) etc. in the collect() below and got compile errors each time. How do I do this ?

public void groupingByDemo() {
    //Split a list of numbers into multiples of 2, 3, 5. Store the result in a Map<Integer, Set>.
    List<Integer> multipliers = Arrays.asList(2, 3, 5);
    List<Integer> nums = Arrays.asList(1, 2, 4, 6, 7, 8, 9, 10, 11, 16, 17, 25, 27);

    Map<Integer, Set> multiples = multipliers
            .stream().collect(
              //What to put here ? or should I use something else instead of collect() ?
            );
}
WJS :

Here is one way to do it.

    List<Integer> multipliers = Arrays.asList(2, 3, 5);
    List<Integer> nums = Arrays.asList(1, 2, 4, 6, 7, 8, 9, 10, 11, 16, 17, 25, 27);

    Map<Integer, Set<Integer>> map = multipliers.stream()
                .collect(Collectors.toMap(m -> m,
                        m-> nums.stream()
                                .filter(n -> n % m == 0)
                                .collect(Collectors.toSet())));
     map.forEach((m, n)-> System.out.println(m + " -> " + n));

Here is the output.

2 -> [16, 2, 4, 6, 8, 10]
3 -> [6, 9, 27]
5 -> [25, 10]       

Guess you like

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