In dieser Aquariumsimulation tue ich so, als wären Minuten Jahre.
Code: Select all
record Turtle(
String name ,
Instant hatched ,
Duration lifespan
)
{
static final Duration MATURITY = Duration.ofMinutes ( 4 );
Duration age ( ) { return Duration.between ( this.hatched , Instant.now ( ) ); }
}
Natürlich dürfen noch keine Schildkröten ausgewachsen sein. Deshalb habe ich den Rückgabetyp als Optional definiert, der leer ist, wenn kein Turtle gefunden wird.
Das Problem ist, dass mein Stream scheinbar fehlschlägt und nie ein Ergebnis zurückgegeben wird . Warum?
Code: Select all
public class Aquarium
{
public static void main ( String[] args )
{
System.out.println ( "INFO Demo start. " + Instant.now ( ) );
// Sample data.
List < Turtle > turtles =
List.of (
new Turtle ( "Alice" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 3 ) ) , Duration.ofMinutes ( 17 ) ) ,
new Turtle ( "Bob" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 2 ) ) , Duration.ofMinutes ( 16 ) ) ,
new Turtle ( "Carol" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 1 ) ) , Duration.ofMinutes ( 18 ) ) ,
new Turtle ( "Davis" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 2 ) ) , Duration.ofMinutes ( 22 ) )
);
System.out.println ( "turtles = " + turtles );
// Logic
Optional < Turtle > anArbitraryMatureTurtle =
ThreadLocalRandom
.current ( )
.ints ( 0 , turtles.size ( ) )
.filter (
( int randomIndex ) -> turtles.get ( randomIndex ).age ( ).compareTo ( Turtle.MATURITY ) > 0
)
.mapToObj ( turtles :: get )
.findAny ( );
System.out.println ( "anArbitraryMatureTurtle = " + anArbitraryMatureTurtle );
// Wrap-up
try { Thread.sleep ( Duration.ofMinutes ( 30 ) ); } catch ( InterruptedException e ) { throw new RuntimeException ( e ); } // Let the aquarium run a while.
System.out.println ( "INFO Demo end. " + Instant.now ( ) );
}
}