收藏家可以给我一个ObservableArrayList吗?有点像这样:
ObservableList<String> newList = list.stream().
filter(x -> x.startsWith("a").
collect(Collectors.toCollection(ObservableArrayList::new));
答案 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));