Java流 - Java流操作

Java Streams - Java Stream Operation

外部迭代 External Iteration

操作Java集合时,我们使用外部迭代。
在外部迭代中,我们使用for或foreach循环,或获取集合的迭代器,处理一个序列的集合元素。

When operating with Java Collections we use external iteration.

In external iteration we use a for or for each loop or obtain an iterator for a collection and process elements of the collections in a sequence.

The following code computes the sum of squares of all odd integers in the list.

It uses for each loop to access every single element in the list then uses if statement to filter odd integers.

After that it calculates the square and finally stores the sum of square with sum variable.

import java.util.Arrays;
import java.util.List;
/*from www .  j a  va  2  s  . c o  m*/
public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = 0;
    for (int n : numbers) {
      if (n % 2 == 1) {
        int square = n * n;
        sum = sum + square;
      }
    }
    System.out.println(sum);
  }
}

The code above generates the following result.
35

内部迭代 Internal Iteration
We can rewrite the code above using stream. It does exactly the same.
import java.util.Arrays;
import java.util.List;
//  w  ww  . java 2  s  .c o m
public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.stream()
        .filter(n -> n % 2  == 1)
        .map(n  -> n * n)
        .reduce(0, Integer::sum);

    System.out.println(sum);
  }
}


在上面的代码中,我们没有使用循环语句来遍历列表。我们用流做内部循环。

对于奇数计算,我们使用lambda表达式。我们首先做了过滤器,然后映射,然后简化。

In the code above we didn't use loop statement to iterate through the List. We did the loop internally by stream.

For the odd integer calculation we used lambda expression. We first did the filter then map then reduce.

The code above generates the following result.
35

连续 Sequential

The external iteration typically means sequential code. The sequential code can be executed only by one thread.

流被设计用于并行处理元素。
Streams are designed to process elements in parallel.

The following code computes the sum of squares of odd integers in the list in parallel.

import java.util.Arrays;
import java.util.List;
//  www  . ja v  a2 s . c om
public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.parallelStream()
        .filter(n -> n % 2  == 1)
        .map(n  -> n * n)
        .reduce(0, Integer::sum);

    System.out.println(sum);
  }
}


What we did is just to replace stream() with parallelStream().

Parallel computation is easy when using the internal iteration provided by the stream.

The code above generates the following result.
35

命令式对比函数式  Imperative vs. Functional

在声明式编程中,我们只需要说明做什么,以及系统本身如何处理其组成部分。

集合支持命令式编程,而流支持声明式编程。

流API通过使用lambda表达式而支持函数式编程。

我们所希望的对流元素执行的操作,通常通过传递一个lambda表达式来完成。

流操作产生结果,而无需修改该数据源。

In imperative programming we control not only what to do but also how to do it.

For example, when using imperative programming to sum integers in a list. We have to decide how to iterate each element in the list. We can use for loop, for-each loop, or we can get an Iterator object from list and use while loop. Then we also have to do the sum.

In declarative programming we just need to tell what to do, the how part is handled by the system itself.

Collections support imperative programming whereas streams support declarative programming.

The Streams API supports the functional programming by using lambda expression.

What operations we want to perform on the stream elements are done typically by passing a lambda expressions.

Operations on a stream produce a result without modifying the data source.

中间操作 和 终端操作

流支持两种类型的操作:

  • 中间操作
  • 终端操作


中间操作也称为懒操作。

终端操作也称为急操作。

懒操作不处理元素,直到在流上被调用急操作。

一个流上的中间操作产生另一个流。

流把不同操作链接起来形成流管道。

在下面的代码中filter()和map()都是懒操作。而reduce()是急操作。

Intermediate operations Terminal operations

A stream supports two types of operations:

  • Intermediate operations
  • Terminal operations


Intermediate operations are also called lazy operations.

Terminal operations are also called eager operations.

A lazy operation does not process the elements until an eager operation is called on the stream.

An intermediate operation on a stream produces another stream.

Streams link operations to create a stream pipeline.

In the following code filter() and map() are all lazy operations. While reduce() is eager operation.

import java.util.Arrays;
import java.util.List;
// ww  w  . j a  v  a  2  s . c om
public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.parallelStream()
        .filter(n -> n % 2  == 1)
        .map(n  -> n * n)
        .reduce(0, Integer::sum);

    System.out.println(sum);
  }
}


The code above generates the following result.
35

来源: http://www.java2s.com/Tutorials/Java/Java_Stream/0020__Java_Stream_Operation.htm

猜你喜欢

转载自jonathan-chen.iteye.com/blog/2225537