如果类别名称相同,则合并图表数据-JavaFX

miniHessel

我有一个可观察到的图表数据列表,它是自动创建的。有什么方法可以自动将具有相同类别名称的数据合并到一个类别中?我之所以需要这样做,是因为可观察的数据列表是直接从SQL数据库中的表创建的,因此我不知道用户是否真的想在图表中显示组合视图或每个类别和值。

说我有以下数据: 在此处输入图片说明

在此处输入图片说明

我不想让Bordeau-1出现那么多次,我希望将所有值组合到一个称为Bordeau-1的饼中,对于Boredeau-2和3也是如此。

这是我用来从代表一个表的ObservableList自动创建数据的代码:

 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);
                }));
詹姆斯_D

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章