gpt4 book ai didi

java - 过滤器上的 map 给出编译问题

转载 作者:行者123 更新时间:2023-11-30 06:25:05 24 4
gpt4 key购买 nike

这里可能出现什么问题?
我在编译时收到以下错误:

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

Stock 类有一个公共(public)方法 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())
);

最佳答案

请确保使用对该方法的完整引用:

Collectors.toList()

或静态导入

import static java.util.stream.Collectors.toList;

以及一个Stock类,有点像:

class Stock {
String symbol;
...
public String getSymbol() {...} //getter for symbol
...
}

Ideone it!

关于java - 过滤器上的 map 给出编译问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47343450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com