javalambdajava-stream

Convert an array into map using stream


I have a list of integers [1,2,3,4,5] and I want to convert it into a map after applying a multiplication function (*5) like this:

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

I was able to use stream and use map function to perform the multiplication but I'm confused about how to convert the result into a map.

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

Can someone please help.


Solution

  • Your current stream pipeline converts the original values to new values, so you can't collect it into a Map that contains both the original values and the new values.

    You can achieve it if instead of map you use .collect(Collectors.toMap()) and perform the multiplication in toMap():

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

    In you still want to use map, you can retain the original values by converting each of them to a Map.Entry:

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