Javaラムダとストリームを使用することにより、多くのマッピングにいずれかを実行するには?

ケーキケーキ:

私は2、3、5の倍数に番号のリストを分割し、地図で結果を保存したいです。出力例は次のようになります。

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

I)は、(収集中(Collectors.groupingBy()を使用して)などをグループ化するさまざまな方法を試み以下、コンパイルエラーを毎回得ました。私はこれをどのように行うのですか?

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:

ここではそれを行うための1つの方法です。

    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));

ここで出力されます。

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=34499&siteId=1