下面的代码给了我一个编译错误
.filter(Book::getPrice >200)
Compilation error is: The target type of this expression should be a functional interface
public void skipData() {
List<Book> bookList = books.stream()
**.filter(Book::getPrice >200)**
.skip(5)
.collect(Collectors.toList());
}
我的 Book.java 类如下所示:
public final class Book {
private String title;
private String genre;
private double price;
public Book(String title, String genre, double price) {
this.title = title;
this.genre = genre;
this.price = price;
}
public double getPrice() {
return price;
}
//other getters
}
我尝试在 Eclipse(火星)和 cmd 行上运行它,并看到了同样的问题。
但是如果我将其更改为 .filter(b -> b.getPrice() >200)
它就可以工作。
我不清楚为什么方法引用在我的情况下不起作用。
最佳答案
Book::getPrice > 200
不是有效的 Java 表达式。
任何可以采用 lambda 表达式作为参数的方法都可以采用以下一个:
- lambda 表达式:
b -> b.getPrice() > 200
- lambda block :
b -> { return b.getPrice() > 200; }
- 方法引用:
Book::isPriceAbove200
- 匿名类:
new Predicate<Book>() { public boolean test(Book b) { return b.getPrice() > 200; }}
方法引用允许重用方法。
关于java - 该表达式的目标类型应该是函数接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32545899/