There is a List list . I want to run through all the elements and double them.

 list.spliterator().forEachRemaining(e -> e*2); 

As a result, my sheet remains unchanged.

I can do it like this:

 List newList = new ArrayList<>(); for(int e in list) { newList.add(e); } 

But the last version is shorter. I want to do this with the help of a lambda function. What are the options?

    1 answer 1

    Here you can without a spliterator . Ways are divided into three types.

    1. change source list

      • .replaceAll() (thanks @zRrr !)

         List<Integer> list = Arrays.asList(1, 2, 3); list.replaceAll(x -> x * 2); 

        (Ideone)

      • It looks like the original version (loop with indexes + methods .get() , .set() ):

         for (int i = 0; i < list.size(); ++i) { int x = list.get(i); list.set(i, x * 2); } 

        (Ideone)

    2. creates a new list with the necessary elements

      • .stream() + .map() + .collect() :

         List<Integer> listTransformed = list .stream() .map(x -> x * 2) .collect(Collectors.toList()); 

        (Ideone)

      • Initial option:

         List<Integer> listTransformed = new ArrayList<>(); for (int x : list) { newList.add(x * 2); } 

        (Ideone)

    3. view object is created above the source list

    Options when the result is an array instead of a list:

    • @zRrr, thanks, all the rest then it turns out not necessary) - diraria
    • one
      do not say that they are not needed, because methods give different results. replaceAll changes the existing list, streams create a new one, transform creates a view above the original list. - zRrr