Last active
January 25, 2023 23:12
-
-
Save akaliacius/c4894de8e8443d1e9768f384a44d05a5 to your computer and use it in GitHub Desktop.
A sipmle Java example. Eager vs lazy evaluation with Supplier interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///usr/bin/env jbang "$0" "$@" ; exit $? | |
import static java.lang.System.*; | |
import java.util.List; | |
import java.util.function.Supplier; | |
import java.util.stream.Stream; | |
public final class SupplierExample { | |
public static void main(String[] args) { | |
var count = 5; | |
eager(UnusedObject.createMany("Eager", count)); | |
lazy(() -> UnusedObject.createMany("Lazy", count)); | |
} | |
private static void eager(List<UnusedObject> list){ | |
System.out.println("Eager thinks it didn't do anything"); | |
} | |
private static void lazy(Supplier<List<UnusedObject>> listSupplier){ | |
System.out.println("Lazy is sure it didn't do anything"); | |
} | |
private static final class UnusedObject { | |
static List<UnusedObject> createMany(String caller, int count){ | |
return Stream.generate(UnusedObject::new) | |
.peek(unusedObject -> System.out.println(caller + " created unused object")) | |
.limit(count) | |
.toList(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment