java stream to list

www.lautt‮iru‬.com
java stream to list

To convert a java.util.stream.Stream to a java.util.List, you can use the collect method with a Collectors.toList() collector. Here's an example:

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

public class StreamToList {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "orange");
        List<String> list = stream.collect(Collectors.toList());
        System.out.println(list);  // prints [apple, banana, orange]
    }
}

You can also use the Collectors.toCollection() method to specify a different type of collection to store the elements of the stream, for example:

import java.util.stream.*;
import java.util.Set;
import java.util.Arrays;
import java.util.stream.Collectors;

public class StreamToSet {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "orange");
        Set<String> set = stream.collect(Collectors.toCollection(HashSet::new));
        System.out.println(set);  // prints [apple, banana, orange]
    }
}

Note that the collect method consumes the stream, so you won't be able to use it again after calling collect. If you need to preserve the stream, you can use the Collectors.toUnmodifiableList() or Collectors.toUnmodifiableSet() collectors instead. These collectors return an unmodifiable view of the list or set, respectively, so you can still iterate over the elements of the stream but you won't be able to modify the collection.

Created Time:2017-10-17 08:54:41  Author:lautturi