使用流将数组转换为映射

时间:2021-05-06 05:28:16

标签: java lambda stream

我有一个整数列表 [1,2,3,4,5],我想在应用乘法函数 (*5) 后将其转换为映射,如下所示:

 {1 = 5, 2 = 10, 3 = 15, 4 = 20, 5 = 25}

我能够使用流和地图函数来执行乘法,但我对如何将结果转换为地图感到困惑。

myList.stream().map(n -> n * 5).collect( ... )

有人可以帮忙吗。

4 个答案:

答案 0 :(得分:5)

您当前的流管道将原始值转换为新值,因此您无法将其收集到同时包含原始值和新值的 Map 中。

如果您使用 map 代替 .collect(Collectors.toMap()) 并在 toMap() 中执行乘法,您可以实现它:

Map<Integer,Integer> map =
    myList.stream()
          .collect(Collectors.toMap(Function.identity(),
                                    n -> n * 5));

如果您仍然想使用 map,您可以通过将每个值转换为 Map.Entry 来保留原始值:

Map<Integer,Integer> map =
    myList.stream()
          .map (n -> new SimpleEntry<> (n, n * 5))
          .collect(Collectors.toMap(Map.Entry::getKey,
                                    Map.Entry::getValue));

答案 1 :(得分:2)

您可以使用 Collectors#toMap 并为值传递任何函数,例如通过使用 UnaryOperator 如下所示:

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        UnaryOperator<Integer> add = x -> x + 5;
        UnaryOperator<Integer> mutiply = x -> x * 5;
        UnaryOperator<Integer> factorial = x -> factorial(x);

        // Test
        List<Integer> list = List.of(1, 2, 3, 4, 5);
        Map<Integer, Integer> map1 = list.stream().collect(Collectors.toMap(Function.identity(), add));
        Map<Integer, Integer> map2 = list.stream().collect(Collectors.toMap(Function.identity(), mutiply));
        Map<Integer, Integer> map3 = list.stream().collect(Collectors.toMap(Function.identity(), factorial));

        System.out.println(map1);
        System.out.println(map2);
        System.out.println(map3);
    }

    static int getValue(int x, UnaryOperator<Integer> function) {
        return function.apply(x);
    }

    static int factorial(int x) {
        if (x <= 0) {
            return 1;
        }
        return x * factorial(x - 1);
    }
}

输出:

{1=6, 2=7, 3=8, 4=9, 5=10}
{1=5, 2=10, 3=15, 4=20, 5=25}
{1=1, 2=2, 3=6, 4=24, 5=120}

答案 2 :(得分:0)

Map<Integer, Long> map = Arrays
        .stream(nums)
        .boxed() // this
        .collect(Collectors.groupingBy(e -> e, Collectors.counting()));

答案 3 :(得分:0)

.collect(Collectors.toMap()) 正是您所需要的。没有 .map。

myList.stream().collect(Collectors.toMap(n-> n, n -> n * 5))

相关问题