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();
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.
A simple method using Stream class
List<T> list = ObservableList<T>.stream().collect(Collectors.toList());
// 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);
// 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));
ObservableList
is a List
. Elements can be added from one list to another at construction time or using the addAll
method.
Apr 25, 2018 at 20:17
ArrayList
, thenArrayList<Consultation> showing = new ArrayList<Consultation>(consultationTable.getItems())
ArrayList<Consultation> showing = new ArrayList<>(consultationTable.getItems());
?ArrayList
? Why notList<Consultation> showing = ...;
? Program to an interface, not an implementation.ObservableList
is backed by anArrayList
anyway (the default way to create one isObservableList<Consultation> obsList = FXCollections.observableArrayList()
or similar.). So what is wrong withList<Consultation> showing = consultationTable.getItems();
. Is there really someArrayList
-specific API you need?