-2

I am doing something simple and cannot figure out how to do it. I have an ArrayList which I used the stream().map() method on and I want to immediately add the results to a new ArrayList.

    List<Integer> list = new ArrayList<>();
    Scanner sc = new Scanner(System.in);

    while (list.size() < 5) {
        System.out.println("Enter numbers of the array : ");
        int num = sc.nextInt();
        list.add(num);
    }
    System.out.print("Before mapping : ");
    list.forEach(a -> System.out.print(a + " "));
    System.out.println("");

    System.out.print("After mapping : ");
    List<Integer> mappedList = new ArrayList<>();
    list.stream().map(n -> n * 3);
    mappedList.forEach(a -> System.out.print(a + " "));

So I want to do something like mappedList = list.stream().map(n -> n * 3); But that is not the right way to do it.

PS advice on any other section of my code would be appreciated too. Thanks!

lczapski
  • 4,026
  • 3
  • 16
  • 32
  • [`Stream::collect`](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.stream.Collector-) – VLAZ Jan 09 '20 at 12:51
  • 1
    You could use something like List collect = list.stream().map(n -> n * 3).collect(Collectors.toList()); – Ivo Jan 09 '20 at 12:53

2 Answers2

1

You can use collect method from java Stream library here.

List<Integer> mappedList = list.stream()
                                .map(n -> n * 3)
                                .collect(Collectors.toList());

More on collect : https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.stream.Collector-

BlackPearl
  • 1,662
  • 1
  • 8
  • 16
0

It will look something like:

public static void main(String[] args) throws Exception {
        List<Integer> list = new ArrayList<>();
        Scanner sc = new Scanner(System.in);

        while (list.size() < 5) {
            System.out.println("Enter numbers of the array : ");
            int num = sc.nextInt();
            list.add(num);
        }
        System.out.print("Before mapping : ");
        list.forEach(a -> System.out.print(a + " "));
        System.out.println("");

        System.out.print("After mapping : ");
        List<Integer> mappedList = new ArrayList<>();
        mappedList = list.stream().map(n -> n * 3).collect(Collectors.toList());

        mappedList.forEach(a -> System.out.print(a + " "));
    }
Andriy Zhuk
  • 133
  • 6