我有一个简单的方法:
public int getPrice(String bookingName)
{
//return the price of a booking
}
我也有课:
public class Booking
{
String name;
...
}
我想将预订分组在地图中(键=预订名称,值= getPrice(bookingName)),所以我这样做了:
public TreeMap<String, Integer> bookingForName() {
return bookings.stream().
collect(Collectors.groupingBy(Booking::getName,Collectors.summingInt(getPrice(Booking::getName))));
}
这不起作用,它说:
这行有多个标记:
- The target type of this expression must be a functional interface
- The method getPrice(String) in the type Manager is not applicable for the arguments `(Booking::getName)`
我能怎么做?谢谢!
您的getPrice()
方法采用String
而非功能接口,因此您无法调用getPrice(Booking::getName)
,即使可以,summingInt
也不接受int
。
更改:
Collectors.summingInt(getPrice(Booking::getName))
至:
Collectors.summingInt(b -> getPrice(b.getName()))
另请注意,Collectors.groupingBy
返回Map
而不是TreeMap
。如果必须有一个TreeMap
,则应调用的其他变体groupingBy
。
public TreeMap<String, Integer> bookingForName() {
return bookings.stream()
.collect(Collectors.groupingBy(Booking::getName,
TreeMap::new,
Collectors.summingInt(b -> getPrice(b.getName()))));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句