Java 8中的消费者lambda

时间:2017-10-24 11:23:50

标签: java-8

Consumer接口适用于T -> void类型的lambda,但在以下代码中是:

lambda Book::getName采用类型:Book->String,我会问为什么它可以充当消费者(List.forEach' s参数是Consumer)。

class Book {
    private String name;

    public Book(String name) {
        this.name = name;
    }

    public String getName() {
        System.out.println(name);
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class BookTest {
    @Test
    public void testBook() {
        List<Book> books  = new ArrayList<>();
        books.add(new Book("A"));
        books.add(new Book("D"));
        books.add(new Book("C"));
        books.add(new Book("B"));

        Function<Book, String> function = Book::getName;
        books.forEach(Book::getName);

        //error here
        //books.forEach(function);

    }
}

2 个答案:

答案 0 :(得分:1)

您可以将非void方法用作使用者。只需丢弃返回值即可will be adapted

答案 1 :(得分:1)

public static void main(String[] args) {
    List<Book> books  = new ArrayList<>();
    books.add(new Book("A"));
    books.add(new Book("D"));
    books.add(new Book("C"));
    books.add(new Book("B"));

    Function<Book, String> function = Book::getName;
    Consumer<Book> consumerFunction = Book::getName;
    books.forEach(Book::getName);

    books.forEach(consumerFunction);

}

您可以尝试这些代码。也许有帮助。