Skip to content
Advertisement

Java List Stream

I am attempting to simplify my code but list stream is not working. I am creating an instance of a class (that contains an inner class) in a static method and trying to take items from the first list and instantiate them in the inner class and add them to a new list. My code works with fruit loops if that matters, I just want to get rid of excess loops. Below is a copy of what I tried.

instance.firstArrayList.stream()
    .map(item -> instance.new Innerclass(item))
    .collect(Collectors.toCollection(() -> instance.secondArrayList));

I am trying to do this multiple times (at least two so far) so simply setting a new ArrayList instance to this won’t work for me. I know I can simply do this with a single loop but I am trying to learn how to use list streams as it has other methods that I find particularly useful and this is the first problem I have run into so far, and I cannot find examples online on this.

Apologies in advance for my poor formatting, this is my first post.

edit(Solved): in the constructor for outerclass, I redeclared the type ArrayList for secondArrayList and that is why it was not working.

Advertisement

Answer

To add all results of your stream to your secondArrayList you could just

    instance.secondArrayList.addAll(instance.firstArrayList.stream()
            .map(item -> instance.new Innerclass(item))
            .toList());

Or alternatively, without intermediate list, adding elements one by one

    instance.firstArrayList.stream()
            .map(item -> instance.new Innerclass(item))
            .forEachOrdered(instance.secondArrayList::add);

Full example (demonstrating both versions):

import java.util.ArrayList;
import java.util.List;

public class Main {
    List<String> firstArrayList = new ArrayList<>();
    List<Innerclass> secondArrayList = new ArrayList<>();
    
    class Innerclass {
        private final String s;

        Innerclass(String s) {
            this.s = s;
        }
        
        @Override
        public String toString() {
            return "I: " + s;
        }
    }
    
    public static void main(String[] args) {
        
        
        Main instance = new Main();

        instance.firstArrayList.addAll(List.of("One", "Two", "Three"));
        
        instance.secondArrayList.addAll(instance.firstArrayList.stream()
                .map(item -> instance.new Innerclass(item))
                .toList());
        
        instance.firstArrayList.stream()
                .map(item -> instance.new Innerclass(item))
                .forEachOrdered(instance.secondArrayList::add);
        
        instance.secondArrayList.forEach(System.out::println);
    }

}

Output:

I: One
I: Two
I: Three
I: One
I: Two
I: Three
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement