【发布时间】:2019-03-21 05:10:16
【问题描述】:
我有下面的代码
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 表达式。
【问题讨论】:
-
diamond operator 使用 Java 已有 4 年了。请使用它。
-
没有这样的构造函数。使用
withInitial(Supplier)并在此处提供 lambda。 -
ThreadLocal<Map<String, Service<Request, Response>>> connectionMapThread = ThreadLocal.withInitial(HashMap::new);