(原)

在上一篇,用到过这样一个方法:

list.forEach(new Consumer<Integer>() {

            @Override
public void accept(Integer t) {
System.out.println(t);
} });

这里重点看List的foreach方法;

/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package java.lang; import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer; /**
* Implementing this interface allows an object to be the target of
* the "for-each loop" statement. See
* <strong>
* <a href="{@docRoot}/../technotes/guides/language/foreach.html">For-each Loop</a>
* </strong>
*
* @param <T> the type of elements returned by the iterator
*
* @since 1.5
* @jls 14.14.2 The enhanced for statement
*/
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
*
* @return an Iterator.
*/
Iterator<T> iterator(); /**
* Performs the given action for each element of the {@code Iterable}
* until all elements have been processed or the action throws an
* exception. Unless otherwise specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
*针对于Iterable的每一个元素去执行给定的动作,直到所有的元素都执行完,或者抛出异常。如果没有被这个实现类所指定,动作就会按照迭代的顺序来执行。是否抛出异常取决于调用者。
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
} /**
* Creates a {@link Spliterator} over the elements described by this
* {@code Iterable}.
*
* @implSpec
* The default implementation creates an
* <em><a href="Spliterator.html#binding">early-binding</a></em>
* spliterator from the iterable's {@code Iterator}. The spliterator
* inherits the <em>fail-fast</em> properties of the iterable's iterator.
*
* @implNote
* The default implementation should usually be overridden. The
* spliterator returned by the default implementation has poor splitting
* capabilities, is unsized, and does not report any spliterator
* characteristics. Implementing classes can nearly always provide a
* better implementation.
*
* @return a {@code Spliterator} over the elements described by this
* {@code Iterable}.
* @since 1.8
*/
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}

  

该方法属于Iterable接口,并且是1.8新加的方法,它有一个默认的实现方法,用关键字default修饰,也就是说,在JDK1.8里,接口方不再必需是抽象方法了,而是可以有实现体的,并且这个有实现体的方法需要用default关键字来修饰。

再来看下Consumer接口。

/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.
*
*代表了一个操作,接收了一个参数,并且不返回结果,不同于大多数其它的函数式接口,Consumer接口期望通过负作用去操作。(也就是说,它可能会操作传入的参数据,这里就是它所说的负作用。)
*
* <p>This is a <a href="package-summary.html">functional interface</a>
* whose functional method is {@link #accept(Object)}.
*这是一个函数式接口,方法是accept
* @param <T> the type of the input to the operation
*
* @since 1.8
*/
@FunctionalInterface
public interface Consumer<T>

  

对于之前的例子,list.forEach(i -> System.out.println(i)); 这个i是什么参数呢?由于这里只有一个参数据,编译器可以自动的推断出这个i所属的类型,同样,你也可以显示的指定它的类型,就像这样list.forEach((Integer i) -> System.out.println(i));,这里是必需要加上括号的。

在其它语言中,lambda表达式类型是函数,但是java中,lambda表达式是对象,他们必需依附于一个函数式接口(functional interface)。

所以对于函数式接口的实现,你可以这么写:

例如有如下函数式接口:

package com.demo.jdk8;

public interface Animal {
void eat(String food);
}

  

在上一篇lambda中,对函数式接口有这样一句话

1、在调用的地方用lambda可以这么写(lamdba expressions):

Animal a = food -> {System.out.println(food);};
a.eat(“鱼”);

这么写和写一个类实现Animal接口,然后再new 出来效是一样的。但是这种写法代码会更简洁。

2、用方法引用可以这么写(method references):

Animal a = System.out::println;
a.eat("肉");

由于java8 ,runbable也改成了一个函数式接口,所以线在的线程可以这么写了:

new Thread(() -> System.out.print("123")).start();

例子请看这里:https://github.com/LeeScofield/java8

Java 8 新特性:2-消费者(Consumer)接口的更多相关文章

  1. Java 8 新特性1-函数式接口

    Java 8 新特性1-函数式接口 (原) Lambda表达式基本结构: (param1,param2,param3) -> {代码块} 例1: package com.demo.jdk8; i ...

  2. Java 8 新特性:1-函数式接口

    (原) Java 8 新特性1-函数式接口 Lambda表达式基本结构: (param1,param2,param3) -> {代码块} Lambda表达式结构: (type1 arg1,typ ...

  3. Java 8新特性-5 内建函数式接口

    在之前的一片博文 Lambda 表达式,提到过Java 8提供的函数式接口.在此文中,将介绍一下Java 8四个最基本的函数式接口 对于方法的引用,严格来讲都需要定义一个接口.不管我们如何操作实际上有 ...

  4. java8新特性学习:函数式接口

    本文概要 什么是函数式接口? 如何定义函数式接口? 常用的函数式接口 函数式接口语法注意事项 总结 1. 什么是函数式接口? 函数式接口其实本质上还是一个接口,但是它是一种特殊的接口:SAM类型的接口 ...

  5. Java JDK1.8新特性之四大函数式接口

    JDK 1.8的一些新特性 四大核心函数式接口(Consumer.Predicate.Supplier.Function),结合lambda表达式 import java.util.ArrayList ...

  6. JAVA 8 新特性实用总JAVA 8 新特性实用总结结

    JAVA 8 新特性实用总结 作为一个工作两年多的 老 程序猿,虽然一开始就使用 jdk1.8 作为学习和使用的版本,随着技术的迭代,现有的 JDK 版本从两年前到现在,已经飞速发展到了 JDK 15 ...

  7. Java 8 新特性概述

    Oracle 在 2014 年 3 月发布了 Java 8 正式版,该版本是一个有重大改变的版本,对 JAVA 带来了诸多新特性.其中主要的新特性涵盖:函数式接口.Lambda 表达式.集合的流式操作 ...

  8. 一小时上手Java 8新特性

    一小时上手Java 8新特性 本文摘译自 https://www.journaldev.com/2389/java-8-features-with-examples,并做了适当增补. Iterable ...

  9. 再来看看Java的新特性——Stream流

    半年前开始试着使用Java的新特性,给我印象最深的就是Stream流和Optional.其中Stream提高了看法效率,让代码看起来十分清爽. 为什么要使用流? 摘要中已经说明了,为了提高开发效率.流 ...

  10. Java 8 新特性——检视阅读

    Java 8 新特性--检视阅读 参考 Java 8 新特性--菜鸟 Oracle 公司于 2014 年 3 月 18 日发布 Java 8 ,它支持函数式编程,新的 JavaScript 引擎,新的 ...

随机推荐

  1. 构建SpringBoot第一个Demo

    使用官方地址生成项目 https://start.spring.io  Generate:可以选择Maven或者Gradle构建项目 语言:我想一般都是Java 接下来选择SpringBoot的版本, ...

  2. python多线程-共享全局变量

    目录 多线程-共享全局变量 多线程-共享全局变量 列表当作实参传递到线程中 总结 多线程-共享全局变量问题 多线程开发可能遇到的问题 测试1 测试2 多线程-共享全局变量 多线程-共享全局变量 imp ...

  3. C#设计模式之十六观察者模式(Observer Pattern)【行为型】

    一.引言 今天是2017年11月份的最后一天,也就是2017年11月30日,利用今天再写一个模式,争取下个月(也就是12月份)把所有的模式写完,2018年,新的一年写一些新的东西.今天我们开始讲“行为 ...

  4. SaaS技术栈的走势

    本地部署时代 在软件还是“本地部署(on-premise)”的时候,SaaS的版图被大型玩家把持着,几乎所有的垂直领域(营销.支持.销售.人力)都被微软.SAP等大公司的解决方案占据.那时候的用户并没 ...

  5. BZOJ2434: [Noi2011]阿狸的打字机(AC自动机 树状数组)

    Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 4140  Solved: 2276[Submit][Status][Discuss] Descript ...

  6. 洛谷P4841 城市规划(生成函数 多项式求逆)

    题意 链接 Sol Orz yyb 一开始想的是直接设\(f_i\)表示\(i\)个点的无向联通图个数,枚举最后一个联通块转移,发现有一种情况转移不到... 正解是先设\(g(n)\)表示\(n\)个 ...

  7. SAP FI配置步骤

    http://blog.sina.com.cn/s/blog_8eda1a620100uwzj.html No. 配置对象 事务代码 配置内容 路径 备注 1 定义公司 OX15 企业结构>定义 ...

  8. 开发Spring过程中几个常见异常(二):Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'a' define

    本异常是小编在运行自己另外一篇博文中的例子时遇到的.(附博文:http://www.cnblogs.com/dudududu/p/8482487.html) 完整异常信息: 警告: Exception ...

  9. 小程序问题集:保存失败:Error: ENOENT: no such file or directory, open

    问题如图: 当编译的时候 会提示找不到这个文件(index),但是确信项目目录里已经删除了该页面路径,并且app.json的pages列表中也没有该页面:   这时候需要看一下当前已经打开的文件中是否 ...

  10. Android项目实战(四十八):架构之组件化开发

    什么要组件化开发? 看一下普通项目的结构 , 一个项目下有多个Module(左侧图黑体目录),但是只有一个application,0个或多个library(在每个medel下的build.gradle ...