我有下面的代码
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread = new ThreadLocal<Map<String, Service<Request, Response>>>() {
@Override
protected Map<String, Service<Request, Response>> initialValue() {
return new HashMap<String, Service<Request, Response>>();
}
};
Run Code Online (Sandbox Code Playgroud)
我想使用 lambda 表达式来编写它,如下所示 -
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = new ThreadLocal<Map<String, Service<Request, Response>>>(() -> new HashMap<String, Service<Request, Response>>());
Run Code Online (Sandbox Code Playgroud)
我尝试了另一种。
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = initialValue() -> {
return new HashMap<String, Service<Request, Response>>();
};
Run Code Online (Sandbox Code Playgroud)
但我收到编译错误。但 IntelliJ Idea 建议这可以写成 lambda 表达式。
ThreadLocal<Map<String, Service<Request, Response>>> test =
ThreadLocal.withInitial(HashMap::new);
Run Code Online (Sandbox Code Playgroud)
您试图将lambda表达式分配给非功能接口,这是行不通的。幸运的是,ThreadLocal提供了一种使用SupplierviawithInitial方法的选项
| 归档时间: |
|
| 查看次数: |
913 次 |
| 最近记录: |