[External] : Gatherers.fold()

Viktor Klang viktor.klang at oracle.com
Thu Jan 2 11:26:08 UTC 2025


Hi Rémi,

>Thinking a little more, i do not understand why fold takes a Supplier as first parameter and not just a value given that the Gatherer is created with ofSequential().

If it didn't take a supplier then the resulting Gatherer could never be reused (including composition). I.e. The use of Supplier for the state type is not primarily/only about parallelizability, but rather reuse (which subsumes parallelizability).

Cheers,
√


Viktor Klang
Software Architect, Java Platform Group
Oracle
________________________________
From: Remi Forax <forax at univ-mlv.fr>
Sent: Friday, 20 December 2024 10:39
To: core-libs-dev <core-libs-dev at openjdk.java.net>
Cc: Viktor Klang <viktor.klang at oracle.com>
Subject: [External] : Gatherers.fold()

Hello Victor,
for the Advent of code of yesterday [1], i've this code golfing solution (the full code is here [2])

  var input = ...;

  class Node {
    final HashMap<Integer, Node> map = new HashMap<>();
    boolean end;
  }
  var root = new Node();
  Arrays.stream(input.substring(0, input.indexOf('\n')).split(", "))
    .forEach(w -> w.chars().boxed().gather(Gatherers.fold(() -> root,
          (n, c) -> n.map.computeIfAbsent(c, _ -> new Node()))).findFirst().orElseThrow().end = true);
  println(input.lines().skip(2).filter(w ->
      w.chars().boxed().<Set<Node>>gather(Gatherers.fold(() -> new HashSet<>(Set.of(root)),
        (ms, c) -> ms.stream().flatMap(m -> Stream.ofNullable(m.map.get(c)))
          .flatMap(n -> n != null && n.end ? Stream.of(n, root) : Stream.ofNullable(n)).collect(Collectors.toSet())))
        .findFirst().orElseThrow().stream().anyMatch(n -> n.end)).count());


As you can see, the second call to Gatherers.fold() requires to specify the type argument, the <Set<Node>> in front because the supplier is not declared as a Supplier<? extends ...>

Thinking a little more, i do not understand why fold takes a Supplier as first parameter and not just a value given that the Gatherer is created with ofSequential().

regards,
Rémi

[1] https://urldefense.com/v3/__https://adventofcode.com/2024/day/19__;!!ACWV5N9M2RV99hQ!J6APK3GQDbT-T1edAyWssnGHideZ-3rnwBQ39CsaHnc0y6OLh0fpSub1gPWjXsfzHl4OfAtxfQvA1k3dUfis$
[2] https://urldefense.com/v3/__https://github.com/forax/advent-of-code-2024__;!!ACWV5N9M2RV99hQ!J6APK3GQDbT-T1edAyWssnGHideZ-3rnwBQ39CsaHnc0y6OLh0fpSub1gPWjXsfzHl4OfAtxfQvA1n-w8kEG$


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20250102/f65436f3/attachment-0001.htm>


More information about the core-libs-dev mailing list