How to convert an observable list to an array list? Java

此生再无相见时 提交于 2020-03-02 09:27:38

问题


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();

回答1:


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.




回答2:


A simple method using Stream class

List<T> list = ObservableList<T>.stream().collect(Collectors.toList());



回答3:


// 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));


来源:https://stackoverflow.com/questions/39872697/how-to-convert-an-observable-list-to-an-array-list-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!