我下面的代码一直在努力理解方法参考。
@GetMapping("/{id}")
public ResponseEntity getCustomerById(@PathVariable("id") Long id) {
Customer customer = customerDAO.get(id);
if (customer == null) {
return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
}
return new ResponseEntity(customer, HttpStatus.OK);
}
当我使用private static String s;
public static void main(String[] args) {
// TODO Auto-generated method stub
LambdaTut lamTut = new LambdaTut();
Function<String, Integer> lenghthFunction = (a) -> a.length();
lamTut.funtionTut(LambdaTut::stringLength);
}
public int stringLength() {
System.out.println(s);
return s.length();
}
public <T, S> void funtionTut(Function<T, S> function) {
Function<T, String> sqFunction = function.andThen(a -> "Length:" + a);
System.out.println(sqFunction.compose((a) -> (T) ("Name:" + a)).apply("Demo"));
}
时,我遇到了一个类强制转换异常,其中Lambdatut::stringLength
可以正常工作。在这里,我很困惑如何用String::length
函数代替函数接口length()
如果我使用S apply(T obj)
,则会出现编译时异常:
LambdaTut类型的funtionTut(Function)方法不适用于参数(lamTut :: stringLength)
答案 0 :(得分:5)
stringLength()
不接受任何参数,它是LambdaTut
的一种方法。因此,LabmdaTut::stringLength
被推断为Function<LambdaTut, Integer>
。
因此,您对funtionTut()
的调用中的通用类型T是LambdaTut。尽管T是LambdaTut,但是您正在将表达式("Name:" + a)
转换为T。那不可能是正确的。
顺便说一句,由于将字符串强制转换为T,这意味着T的唯一可能类型是String,Object,Serializable等,并且通用类型T甚至不应该存在。该方法应声明为
public <S> void funtionTut(Function<String, S> function)
关于lamTut::stringLength
,由于stringLength()
不接受任何参数,因此它是一个不接受任何输入并返回Integer的函数。因此,可以将其推断为Supplier<Integer>
,而不是函数,因为函数需要输入。
答案 1 :(得分:-1)
在上面的代码中
此方法仅使用实例字符串长度返回整数
import pandas as pd
df = pd.read_csv('/home/Peter/hi/hi2/data/cocktails.csv', delimiter=';', quotechar='|', index_col='revision_id')
df['timestamp'] = pd.to_datetime(df['timestamp'])
# Filter out anonymous users:
df = df[df['contributor_name'] != 'Anonymous']
# get the number of edits each user has done each month: this is a series
editions_per_user_monthly = df.groupby([pd.Grouper(key='timestamp', freq='MS'), pd.Grouper(key='contributor_name')]).size()
# filter users with number >= requested
df2 = (editions_per_user_monthly[editions_per_user_monthly >= 5]).to_frame(name='pages_edited')
但是使用
> Blockquote series = df2.apply(lambda x: len(x))
functionTut无法确定数据类型
只需更改功能
public int stringLength() {
System.out.println(s);
return s.length();
}
它的工作