0

I have the below code

      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>>();
        }
    };

I want to write it using lambda expression like below -

ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = new ThreadLocal<Map<String, Service<Request, Response>>>(() -> new HashMap<String, Service<Request, Response>>());

I tried another one.

ThreadLocal<Map<String, Service<Request, Response>>> connectinonMapThread2 = initialValue() -> {

            return new HashMap<String, Service<Request, Response>>();
    };

But I am getting compilation error. But the IntelliJ Idea suggests this could be written as lambda expression.

Intellij Idea Suggestion

user51
  • 8,843
  • 21
  • 79
  • 158

1 Answers1

5
ThreadLocal<Map<String, Service<Request, Response>>> test = 
            ThreadLocal.withInitial(HashMap::new);

You are trying to assign a lambda expression to a non-functional interface, this will not work. Fortunately ThreadLocal offers one option with a Supplier via withInitial method

Eugene
  • 117,005
  • 15
  • 201
  • 306