我有以下代码
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>>();
}
};
我想使用如下所示的lambda表达式编写它-
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = new ThreadLocal<Map<String, Service<Request, Response>>>(() -> new HashMap<String, Service<Request, Response>>());
我尝试了另一个。
ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = initialValue() -> {
return new HashMap<String, Service<Request, Response>>();
};
但是我遇到编译错误。但是IntelliJ Idea建议这可以写为lambda表达式。
答案 0 :(得分:1)
magic
您试图将ThreadLocal<Map<String, Service<Request, Response>>> test =
ThreadLocal.withInitial(HashMap::new);
表达式分配给非功能性接口,这将不起作用。幸运的是,lambda
通过ThreadLocal
方法为Supplier
提供了一个选项