79631639

Date: 2025-05-21 09:10:32
Score: 1
Natty:
Report link

A great shame Java doesn't (yet) have support for this.

Here's an example, how this can be achieved with a POJO Stream.:

package org.stackoverflow;

import java.time.Clock;
import java.time.Instant;
import java.util.Comparator;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.IntStream;

public class StackOverflow_69450027 {

    private static record InstantHolder(int i, Instant instant, int remainder) {}

    public static void main(final String[] args) {

        final var gotZero     = new AtomicBoolean(false);

        final var holderArray = IntStream.range(0, 10_000) // (Range must not be empty!)
                .mapToObj(i -> {
                    if (gotZero.get()) { // Previous Iteration yielded desired result...
                        return null;     // ...so we can trigger the "takeWhile" escape.
                    }
                    final var instant   = Clock.systemUTC().instant();
                    final var remainder = instant.getNano() % 1_000;

                    if (remainder == 0) {  // Trigger "takeWhile" escape NEXT ITERATION?
                        gotZero.set(true); // (but this first 0 will be accepted)
                    }
                    final var holder    = new InstantHolder(i, instant, remainder);

                    System.out.println("peek......: " + holder);

                    return    holder;
                })
                .takeWhile(                        holder -> holder != null)    // "takeWhile" escape
                .sorted   (Comparator.comparingInt(holder -> holder.remainder))
                .toArray  (InstantHolder[] :: new);
        /*
         * The resulting Array will always have at least 1 entry.
         * As the entries were sorted, entry [0] will contain the Result with the least Remainder...
         */
        System.out.println("** RESULT.: " + holderArray[0]);
    }
}

Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Blacklisted phrase (1): StackOverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Dave The Dane