java 如何将可观察列表转换为数组列表?爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39872697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an observable list to an array list? Java
提问by Philayyy
I'm trying to get all the items in a table view and place them in an array list for further processing. This is what I'm trying to achieve but obviously it won't work.
我正在尝试获取表视图中的所有项目并将它们放在数组列表中以供进一步处理。这就是我想要实现的目标,但显然它行不通。
ArrayList<Consultation> showing = consultationTable.getItems();
回答by Ole V.V.
Nice and recommended solution:
不错的推荐解决方案:
List<Consultation> showing = provider.getItems();
Solution to use only if necessary:
仅在必要时使用的解决方案:
List<Consultation> consultations = provider.getItems();
ArrayList<Consultation> showing;
if (consultations instanceof ArrayList<?>) {
showing = (ArrayList<Consultation>) consultations;
} else {
showing = new ArrayList<>(consultations);
}
If for some reason you need to use an ArrayList method that is not in the List or ObservableList interface (I cannot readily think of why), you may use the latter.
如果由于某种原因您需要使用不在 List 或 ObservableList 接口中的 ArrayList 方法(我想不出为什么),您可以使用后者。
回答by Jason Amade
A simple method using Stream class
使用Stream类的简单方法
List<T> list = ObservableList<T>.stream().collect(Collectors.toList());
回答by Maude Volk
// To convert an observable list to an array of strings given the following observable list:
// Create these in the class
ListView<String> myListView = new ListView<>();
ObservableList<String> myList;
// Then define them in the start class myList = FXCollections.observableArrayList(someGivenArray); myListView.setItems(myList);
// 然后在开始类中定义它们 myList = FXCollections.observableArrayList(someGivenArray); myListView.setItems(myList);
// Make an array to store list items in the observable list as strings
List<String> myArray = new ArrayList<String>();
// Loop through the observable list and load the string array
for (int i =0; i<myList.size(); i++){
myArray.add(myList.get(i));
}
// Test by printing out to the screen or a text field
System.out.println(myList.get(0));
myTextField.setText(myList.get(0));