Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 reports "cannot resolve constructor" by calling "::new"

In Intellij 15.0.3. and using Java8 I have a problem in using ::new. In particular, I have a class with a default constructor

public class Container{

  public Container(){}

} 

I want to create a map from a list, as follows:

public class Test{
  private final Map<Key, Container> map;

  @Before
  public void setUp(){
    List<Key> keys=...//Init the list
     map = keys.stream().collect(Collectors.toMap(Function.identity(), Container::new));


  }

}

In Intellij, new is red and the tooltip says cannot resolve constructor Container

If I do () -> {new Container()} I also have cannot infer functional interface type Container

Any idea why?

like image 920
mat_boy Avatar asked Oct 22 '25 12:10

mat_boy


1 Answers

Each mapping function is supposed to accept a Key argument. Function.identity() does, but Container::new takes no parameters. Same thing with () -> new Container(). You need a one-argument lambda. An argument that you'll ignore, as it happens.

map = keys.stream().collect(Collectors.toMap(Function.identity(), key -> new Container()));
like image 200
John Kugelman Avatar answered Oct 25 '25 20:10

John Kugelman