So, you’ve been planning to learn the new stuff made available in Java 8. One of them is the Stream interface. Given a collection, e.g., List, a Stream can be extracted using
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8StreamToList { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("1"); list.add("2"); Stream<String> myStream = list.stream(); // Displays [1, 2] System.out.println(myStream.collect(Collectors.toList())); } } |
If you wish not to create an initial list, you may use Stream.of(T... values).
For example,
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8StreamToList2 { public static void main(String[] args) { Stream<String> myStream = Stream.of("1", "2"); // Displays [1, 2] System.out.println(myStream.collect(Collectors.toList())); } } |