Combine chart data if category name is the same - JavaFX

≯℡__Kan透↙ 提交于 2019-12-25 16:03:20

问题


I have an observable list of chart data which is created automatically. Is there any way to automatically combine the data which has the same category name in to one category? The reason I need this is since the observable list of data is created directly form a table in a SQL database, I can not know if the user actually wants to show a combined view or each category and value separately in the chart.

Say I have the following data:

Instead of Bordeau-1 appearing this many times, I want all the values combined in to one pie called Bordeau-1, the same goes for Boredeau-2 and 3.

This is the code I use to automatically create data from the ObservableList which represents a table:

 ObservableList<PieChart.Data> pieChartData
                = 
FXCollections.observableArrayList(EasyBind.map(observableListData, rowData -> {
                    String name = (String) rowData.get(0);
                  Double value = Double.parseDouble(rowData.get(1));
                    return new PieChart.Data(name, value);
                }));

回答1:


When you load the data, store it in a Map<String, Double>, and use the Map.merge(...) method to add or combine new values.

So in the code where you are loading the data from the database, you do this:

public Map<String, Double> loadDataFromDatabase() {
    Map<String, Double> data = new HashMap<>();
    // for each row in database:
        // get name and value from row
        data.merge(name, value, Double::sum);
    // end for...
    return data ;
}

Once you have loaded all the data into the map, you need to convert it to an ObservableList<PieChart.Data>. I don't think there's a cute way to do this in EasyBind, and if you're loading all the data at the start anyway, then you don't need the bound list. You can do something like:

ObservableList<PieChart.Data> pieChartData =
    data.entrySet().stream()
    .map(entry -> new PieChart.Data(entry.getKey(), entry.getValue()))
    .collect(Collectors.toCollection(() -> FXCollections.observableArrayList()));

If the original map may get modified after the pie chart is created, you will need to make it an ObservableMap, register a listener with it, and update the pie chart data accordingly if the map changes. If you need this, it might be worth requesting the appropriate functionality in the EasyBind framework. Something like a method

public static <K, V, T> ObservableList<T> mapToList(ObservableMap<K, V> map, Function<Map.Entry<K, V>, T> mapping);


来源:https://stackoverflow.com/questions/26507675/combine-chart-data-if-category-name-is-the-same-javafx

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