lambda foreach添加到地图不起作用

时间:2015-01-19 19:44:30

标签: java javafx-8

我有以下变量

List<Pruefvorschrift> listP = new ArrayList<Pruefvorschrift>();
ObservableMap<TestDevice,List<Pruefvorschrift>> testDev = FXCollections.emptyObservableMap();

在一个函数中我想用lambda表达式填充testDev

//first call REST service and get data
List<TestDevice> test_dev = call.getTestDevice("");
//now do a foreach to add each entry (as key) to the testDev ObservableMap with a empty List (as value)
test_dev.stream().forEach(td ->{
                    TestDevice t = td;                    
                    testDev.put(t, listP);
            });

但我得到的只是一个错误

  

java.lang.UnsupportedOperationException at   java.util.AbstractMap.put(AbstractMap.java:209)

这显然就是这一行

 testDev.put(t, listP);

也许我误解了新的流api但我只想填充可观察的地图,其中包含所有调用的结果(键)和一个空的List(稍后将修改的值)。 有帮助吗? THX

2 个答案:

答案 0 :(得分:5)

FXCollections#emptyObservableMap

返回的Map类型
FXCollections.emptyObservableMap();

不支持put方法。你不能添加任何东西。正如javadoc所述

  

创建和[sic]空的不可修改的可观察列表。

这与lambda表达式或Stream api无关。

答案 1 :(得分:0)

就在这里完成(Sotirios Delimanolis是绝对正确的,我错了:)。通过使用地图本身做正确的工作来解决我的问题

//create empty map
Map<TestDevice,List<Pruefvorschrift>> map = new HashMap<TestDevice,List<Pruefvorschrift>>();
//use this map to create the ObservableMap
ObservableMap<TestDevice,List<Pruefvorschrift>> testDev = FXCollections.observableMap(map);

所有作品...... Thx Sotirios