Search code examples
javajavafxjavafx-8

Find maximum Y in JavaFX XYSeries


series.getData().add(new XYChart.Data(x ,function(x));

I try to get maximum of function(x); I know I can use "series.getData().sort"

But when I write

series.getData().sort(Comparator.comparingDouble(d -> d.getYValue().doubleValue()));

it said that can't resolve method getYValue; How to solve this problem ?


Solution

  • It's unlikely that you want to sort the data, which would likely distort the chart's meaning. Instead, get a stream of data from the desired series and invoke the max() method, as @fabian suggests.

    Using data from ensemble.samples.charts.line.chart.LineChartApp as an example,

    ObservableList<XYChart.Series<Double, Double>> lineChartData = FXCollections.observableArrayList(
        new LineChart.Series<>("Series 1", FXCollections.observableArrayList(
            new XYChart.Data<>(0.0, 1.0),
            new XYChart.Data<>(1.2, 1.4),
            new XYChart.Data<>(2.2, 1.9),
            new XYChart.Data<>(2.7, 2.3), //max
            new XYChart.Data<>(2.9, 0.5))),
        new LineChart.Series<>("Series 2", FXCollections.observableArrayList(
            new XYChart.Data<>(0.0, 1.6),
            new XYChart.Data<>(0.8, 0.4),
            new XYChart.Data<>(1.4, 2.9), //max
            new XYChart.Data<>(2.1, 1.3),
            new XYChart.Data<>(2.6, 0.9)))
        );
    

    The following fragment produces the expected output forEach() series.

    lineChartData.forEach((series) -> {
        System.out.println(series.getData().stream().max(
            Comparator.comparing(XYChart.Data::getYValue)).get().getYValue());
    });
    

    Console:

    2.3
    2.9