D
D
dc65k2020-10-16 13:46:22
Java
dc65k, 2020-10-16 13:46:22

What is the correct way to work with List data using Stream API?

Hello. Please tell me how to correct the code in order to work with data, in this case with List. I wrote three, two of which are commented out, but I understand that the problem is the same everywhere.

package stream;

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

public class Test5 {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add(3);
        list.add(8);
        list.add(1);
        list.add(5);
        list.add(9);

        List result = filterArray(list);

        System.out.println(result);
    }

    public static List filterArray(List list) {
        System.out.println(list);

        List result;

//        list.stream()
//            .forEach(element -> {
//                System.out.println(element);
//                result.add(element);
//            });

//        list.stream()
//            .map(element -> {
//                return element * 2;
//            })
//            .forEach(element -> {
//                result.add(element);
//            });

        list.stream()
            .filter(element -> {
                return element % 2 == 0;
            })
            .forEach(element -> {
                result.add(element);
            });

        return result;
    }
}


I will add that the question is exactly if I initially work with List.
With the option, if you initialize the values ​​​​in the stream, I figured it out.
public class Test6 {
    public static void main(String[] args) {
        Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 1, 2);

        List result;

        result = stream1
                .filter(el -> {
                    System.out.println("!!!");
                    return el % 2 == 0;
                })
                .map(element -> {
                    return element * 2;
                })
                .collect(Collectors.toList());

        System.out.println(result);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-10-16
@dc65k

return list.stream()
    .filter(....)
    .collect(Collectors.toList());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question