Stream confusion
Archie Cobbs
archie.cobbs at gmail.com
Wed Nov 22 16:25:00 UTC 2023
Argh, sorry I pasted the wrong example. The Widget fields "color" and
"weight" are supposed to NOT be final:
@@ -5,8 +5,8 @@
public class Widget {
- private final Color color;
- private final int weight;
+ private Color color;
+ private int weight;
public Widget(Color color, int weight) {
this.color = color;
The question remains the same - is the program deterministic?
-Archie
On Wed, Nov 22, 2023 at 10:06 AM Archie Cobbs <archie.cobbs at gmail.com>
wrote:
> I have an API design question about Streams, but instead of asking the
> question outright I thought I'd ask it indirectly with a simple example.
>
> The Javadoc for Stream opens with this example:
>
> int sum = widgets.stream()
> .filter(w -> w.getColor() == RED)
> .mapToInt(w -> w.getWeight())
> .sum();
>
> OK, looks reasonable - we're computing the sum of the weights of all the
> red widgets.
>
> Here's the question: Is the following program deterministic?
>
> import java.awt.*;
> import java.util.function.*;
> import java.util.stream.*;
> import static java.awt.Color.*;
>
> public class Widget {
>
> private final Color color;
> private final int weight;
>
> public Widget(Color color, int weight) {
> this.color = color;
> this.weight = weight;
> }
>
> public Color getColor() {
> return this.color;
> }
>
> public int getWeight() {
> return this.weight;
> }
>
> public static int totalRedWeight(Widget... widgets) {
> return Stream.of(widgets)
> .filter(w -> w.getColor() == RED)
> .mapToInt(w -> w.getWeight())
> .sum();
> }
>
> // Test method
>
> public static void main(String[] args) {
> final Widget w1 = new Widget(RED, 123);
> final Widget w2 = new Widget(BLUE, 456);
> final int total = Widget.totalRedWeight(w1, w2);
> System.out.println("Total red weight = " + total);
> }
> }
>
> -Archie
>
> --
> Archie L. Cobbs
>
--
Archie L. Cobbs
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20231122/fa16df68/attachment.htm>
More information about the amber-dev
mailing list