From 44f6a189d4e5f22beb4d5a4598203e703038eb29 Mon Sep 17 00:00:00 2001 From: Giambo Date: Fri, 7 Jun 2024 10:57:30 +0200 Subject: [PATCH] Avoid call to to Chart#getSeriesMap (Marked for removal) --- .../xchart/demo/charts/pie/PieChart02.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/pie/PieChart02.java b/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/pie/PieChart02.java index 5ef25bb4..ba7e1e56 100644 --- a/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/pie/PieChart02.java +++ b/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/pie/PieChart02.java @@ -3,6 +3,7 @@ import java.awt.Color; import java.util.Collection; import java.util.function.Function; +import java.util.stream.Stream; import org.knowm.xchart.PieChart; import org.knowm.xchart.PieChartBuilder; @@ -39,11 +40,13 @@ public PieChart getChart() { new PieChartBuilder().width(800).height(600).title(getClass().getSimpleName()).build(); // Series - chart.addSeries("Gold", 24); - chart.addSeries("Silver", 21); - chart.addSeries("Platinum", 39); - chart.addSeries("Copper", 17); - chart.addSeries("Zinc", 40); + int total = Stream.of( + chart.addSeries("Gold", 24), + chart.addSeries("Silver", 21), + chart.addSeries("Platinum", 39), + chart.addSeries("Copper", 17), + chart.addSeries("Zinc", 40) + ).map(PieSeries::getValue).mapToInt(Number::intValue).sum(); // Customize Chart Color[] sliceColors = @@ -55,7 +58,7 @@ public PieChart getChart() { new Color(246, 199, 182) }; chart.getStyler().setSeriesColors(sliceColors); - chart.getStyler().setCustomSeriesLabelFunction(generateSeriesLabel(chart.getSeriesMap().values())); + chart.getStyler().setCustomSeriesLabelFunction(generateSeriesLabel(total)); // chart.getStyler().setDecimalPattern("#0.000"); chart.getStyler().setToolTipsEnabled(true); // chart.getStyler().setToolTipsAlwaysVisible(true); @@ -69,8 +72,7 @@ public String getExampleChartName() { return getClass().getSimpleName() + " - Pie Chart Custom Color Palette"; } - private Function generateSeriesLabel(Collection values) { - double total = values.stream().map(PieSeries::getValue).mapToDouble(Number::doubleValue).sum(); + private Function generateSeriesLabel(int total) { return pieSeries -> { double percent = (pieSeries.getValue().doubleValue() / total) * 100; return String.format("%s (%.2f%%)", pieSeries.getValue(), percent);