现在要对下面一组 number ,过滤掉被5整除的,再*2 .
jdk1.7 之前是这么做的:
public static void main(String... args){ List<Integer> values = Arrays.asList(11,22,33,44,55,60,75); int result = 0; for (int i : values) { if(i % 5 == 0){ result += i; } } System.out.println(result); }
如果我们以这种方式去实现的话,forEach 循环里的 code 我们把它称为 embedded recording ,意味着你要 focus on what to do and how to do,但是到了 jdk 1.8,使用 Stream API后,它的理念是不需要 focus on how to do , 只需要 focus on what to do .看下面的代码,而且上面的 code 还是属于 external iteration ,data 多的时候效率相比于下面的 internal ireration 要慢许多,这也是 Stream API 的一个优点。
System.out.println(values.stream() .filter(i -> i%5==0) .map(i -> i*2));
看一下 filter method :
Returns a stream consisting of the elements of this stream that match the given predicate.
public interface Stream<T> extends BaseStream<T, Stream<T>> { /** * Returns a stream consisting of the elements of this stream that match * the given predicate. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to each element to determine if it * should be included * @return the new stream */ Stream<T> filter(Predicate<? super T> predicate);
对于 Predicate Interface : 它是一个 functional interface,只有一个 test method ,takes a parameter and return boolean.所以上面的 filter是这样实现的:
/** * Represents a predicate (boolean-valued function) of one argument. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #test(Object)}. * * @param <T> the type of the input to the predicate * * @since 1.8 */ @FunctionalInterface public interface Predicate<T> { /** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */ boolean test(T t);
Predicate<Integer> p = new Predicate<Integer>() { @Override public boolean test(Integer i) { return i%5 == 0; } };
再用 lambda expression 把 p 替换掉就成了:
System.out.println(values.stream() .filter(i -> i%5==0) .map(i -> i*2) .reduce(Integer::sum));
所以从总体上来看,在使用 Stream API 时,实际上变成了函数式编程,没有 focus on Object,而是 focus on functions,
.stream()、.filter()、.map()、.reduce() 四个 function ,像是不用再去 create object了。
更多请看这里:http://docs.oracle.com/javase/8/docs/api/