Home >Java >javaTutorial >How to use Stream in java and what to pay attention to
1. Use process, instantiation of Stream, and a series of intermediate operations. Terminate operation
2. Note that intermediate operation chain processes the data from the data source. Once the termination operation is performed, the chain of intermediate operations is executed and results are produced. After that, it will not be used again.
Example
public class StreamAPITest1 { //创建 Stream方式一:通过集合 @Test public void test1() { List<Employee> employees = EmployeeData.getEmployees(); //efault Stream<E> stream() : 返回一个顺序流 Stream<Employee> stream = employees.stream(); //default Stream<E> parallelStream() : 返回一个并行流 Stream<Employee> employeeStream = employees.parallelStream(); } //创建 Stream方式二:通过数组 @Test public void test2() { int[] arrs = {1, 2, 3, 6, 2}; //调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流 IntStream stream = Arrays.stream(arrs); Employee e1 = new Employee(1001, "Tom"); Employee e2 = new Employee(1002, "Jerry"); Employee[] employees = {e1, e2}; Stream<Employee> stream1 = Arrays.stream(employees); } //创建 Stream方式三:通过Stream的of() @Test public void test3() { Stream<Integer> integerStream = Stream.of(12, 34, 45, 65, 76); } //创建 Stream方式四:创建流 @Test public void test4() { //迭代 //public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) //遍历前10个偶数 Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println); //生成 //public static<T> Stream<T> generate(Supplier<T> s) Stream.generate(Math::random).limit(10).forEach(System.out::println); } }
The above is the detailed content of How to use Stream in java and what to pay attention to. For more information, please follow other related articles on the PHP Chinese website!