2016-04-26 77 views
2

In Intellij 15.0.3。並使用Java8我在使用::new時遇到問題。 特別是,我有一個類有一個默認的構造Java8報告「無法通過調用」:: new「解析構造函數」

public class Container{ 

    public Container(){} 

} 

我想創建一個列表中的地圖,如下所示:

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


    } 

} 

在的IntelliJ,new爲紅色,提示說:cannot resolve constructor Container

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

任何想法,爲什麼?

回答

3

每個映射函數應該接受Key參數。 Function.identity()確實,但Container::new沒有參數。與() -> new Container()同樣的事情。你需要一個單參數的lambda。一個你會忽略的論點,就像它發生的那樣。

map = keys.stream().collect(Collectors.toMap(Function.identity(), key -> new Container())); 
-2

它應該是這樣的:

Collectors.toMap(Container::getMyUniqueField, Function.identity()) 

這將使用getter鑰匙,和對象本身的價值,在創建的HashMap中。

+0

'toMap'有兩個參數。第一個是_keyMapper_(所以我有'Function.identity()',第二個是_valueMapper_,它必須返回一個新的'Container'類的實例,你正在反轉鍵和值 –

+0

正是你想要的沒有道理 – NimChimpsky

相關問題