Java8 通过调用“::new”报告“无法解析构造函数”

mat*_*boy 3 intellij-idea java-8

在 Intellij 15.0.3 中。并且使用 Java8 我在使用::new. 特别是,我有一个带有默认构造函数的类

public class Container{

  public Container(){}

} 
Run Code Online (Sandbox Code Playgroud)

我想从列表中创建地图,如下所示:

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


  }

}
Run Code Online (Sandbox Code Playgroud)

在 Intellij 中,new是红色的,工具提示说cannot resolve constructor Container

如果我这样做,() -> {new Container()}我也有cannot infer functional interface type Container

知道为什么吗?

Joh*_*ica 5

每个映射函数都应该接受一个Key参数。Function.identity()可以,但Container::new不带参数。与() -> new Container(). 您需要一个单参数 lambda。一个你会忽略的论点,因为它发生了。

map = keys.stream().collect(Collectors.toMap(Function.identity(), key -> new Container()));
Run Code Online (Sandbox Code Playgroud)