1
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 ?

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
熊凯昕
  • 13
  • 4
  • 3
    Probably you used the raw type in the declaration of `series`. BTW: you don't need to sort the list to find the max. You could use the `max` method of the stream api: `series.getData().stream().max(Comparator.comparing(XYChart.Data::getYValue)).orElse(null)` – fabian Dec 20 '18 at 10:35
  • it seems that there were something wrong with "XYChart.Data::getYValue",it said non-static method can't be referenced from a static context, and what do you mean I use raw type in the declaration of "series"? XYChart.Series series = new XYChart.Series(); – 熊凯昕 Dec 20 '18 at 11:17
  • `XYChart.Series` is a generic class but you don't specify the generic parameters. See [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). – Slaw Dec 20 '18 at 11:43

1 Answers1

1

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
trashgod
  • 203,806
  • 29
  • 246
  • 1,045