Answer the question
In order to leave comments, you need to log in
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;
}
}
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
return list.stream()
.filter(....)
.collect(Collectors.toList());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question