这可能是什么问题?
我在编译时遇到以下错误:
error: cannot find symbol
.collect(toList())
^
symbol: method toList()
location: class stocks
error: invalid method reference
.map(Stock::getSymbol)
^
cannot find symbol
symbol: method getSymbol()
location: class Stock
Class Stock有一个公共方法getSymbol
static class StockUtil{
public static Predicate<Stock> isLessThanLimit(Double limit){
return s -> s.tick < limit;
}
public static String toUpperCase(String stock){
return stock.toUpperCase();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Stock> stocks = new ArrayList<>(Arrays.asList(new Stock("AMZ",312.0),
new Stock("Yahoo",212.0),
new Stock("ORCL",512.0),
new Stock("SAP",112.0),
new Stock("Google",412.0),
new Stock("FB",12.0),
new Stock("TWT",315.0)));
//print list of stock names below 400 in uppercase
System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
.map(Stock::getSymbol)
.map(StockUtil::toUpperCase)
.collect(toList())
);
答案 0 :(得分:1)
要么确保使用方法的完整参考
Collectors.toList()
或静态导入
import static java.util.stream.Collectors.toList;
以及Stock
类有点像:
class Stock {
String symbol;
...
public String getSymbol() {...} //getter for symbol
...
}
答案 1 :(得分:0)
您尚未定义方法toList()
,或者您忘记执行静态导入,请尝试:
import static java.util.stream.Collectors.toList;
您的代码中不需要进行任何其他更改。
如果您不想进行静态导入:
System.out.println(stocks.stream().filter(StockUtil.isLessThanLimit(400.0))
.map(Stock::getSymbol)
.map(StockUtil::toUpperCase)
.collect(Collectors.toList())
);
有关详细信息,请参阅收集器的java documentation。