Streams from Collections

Description

The Collection interface contains the stream() and parallelStream() methods that create sequential and parallel streams from a Collection, respectively.

Example

The following code creates streams from a set of strings:


import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
/* w w w.j  a v a 2  s.  c o  m*/
public class Main {
  public static void main(String[] args) {
    Set<String> names = new HashSet<>(); 
    names.add("XML");
    names.add("Java");

    Stream<String> sequentialStream  = names.stream();
    sequentialStream.forEach(System.out::println);

    Stream<String> parallelStream = names.parallelStream();
    parallelStream.forEach(System.out::println);
  }
}

The code above generates the following result.





















Home »
  Java Streams »
    Tutorial »




Java Streams Tutorial