收藏家lambda返回可观察列表

时间:2015-11-21 22:49:52

标签: java lambda java-8 observablelist collectors

收藏家可以给我一个ObservableArrayList吗?有点像这样:

ObservableList<String> newList = list.stream().
        filter(x -> x.startsWith("a").
        collect(Collectors.toCollection(ObservableArrayList::new));

1 个答案:

答案 0 :(得分:17)

ObservableList是使用FXCollections类中的静态工厂创建的。

您可以执行以下操作,首先将流收集到List中,然后将其封装在ObservableList内。

ObservableList<String> newList = 
        list.stream()
            .filter(x -> x.startsWith("a"))
            .collect(Collectors.collectingAndThen(toList(), l -> FXCollections.observableArrayList(l)));

(遗憾的是,它不能在Eclipse Mars 4.5.1上编译,但在javac 1.8.0_60上编译得很好。

另一种可能性是为此创建自定义收集器。这样做的优点是不需要首先使用List。这些元素直接收集在ObservableList

ObservableList<String> newList = 
        list.stream()
            .filter(x -> x.startsWith("a"))
            .collect(Collector.of(
                FXCollections::observableArrayList,
                ObservableList::add,
                (l1, l2) -> { l1.addAll(l2); return l1; })
            );

正如Louis Wasserman in the comments所指出的,可以使用toCollection更简单地重写最后一个表达式:

ObservableList<String> newList = 
        list.stream()
            .filter(x -> x.startsWith("a"))
            .collect(Collectors.toCollection(FXCollections::observableArrayList));