#255 Modifying an Object After Stream Filtering

Companies:
Digitalleague
Themes:
JavaStreams & LambdasCode Review

What will be printed?

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    static class A {
        int a;

        A(int a) {
            this.a = a;
        }

        @Override
        public String toString() {
            return "{" + a + "}";
        }
    }

    public static void main(String[] args) {
        List<A> list1 = Arrays.asList(new A(1), new A(2));
        List<A> list2 = list1.stream()
                .filter(elem -> elem.a == 1)
                .collect(Collectors.toList());
        list2.get(0).a = 4;
        System.out.println(list1);
        System.out.println(list2);
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in