Basics, failure semantics on 26 vs 27, lazy collections, API across 25/26/27, preview-flag traps and a JMH read-path benchmark (jars fetched and sha1-checked, not committed). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01TF9JWFvJSNm6HVzswzZU5a
26 lines
1.4 KiB
Java
26 lines
1.4 KiB
Java
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Set;
|
|
|
|
// List.ofLazy, Map.ofLazy (JDK 26 and 27) and Set.ofLazy (new in JDK 27): each element is computed on first access.
|
|
public class LazyCollections {
|
|
public static void main(String[] args) {
|
|
List<String> list = List.ofLazy(3, i -> { System.out.println(" computing list element " + i); return "v" + i; });
|
|
System.out.println("list created, size " + list.size() + " (nothing computed yet)");
|
|
System.out.println("list.get(1) = " + list.get(1));
|
|
System.out.println("list.get(1) again = " + list.get(1));
|
|
|
|
Map<String, Integer> map = Map.ofLazy(Set.of("a", "bb", "ccc"), k -> { System.out.println(" computing map value for " + k); return k.length(); });
|
|
System.out.println("map created, size " + map.size() + " (nothing computed yet)");
|
|
System.out.println("map.get(\"bb\") = " + map.get("bb"));
|
|
System.out.println("map.get(\"bb\") again = " + map.get("bb"));
|
|
|
|
Set<Integer> set = Set.ofLazy(Set.of(1, 2, 3), n -> { System.out.println(" testing " + n); return n > 1; });
|
|
System.out.println("set created");
|
|
System.out.println("set.contains(2) = " + set.contains(2));
|
|
System.out.println("set.contains(1) = " + set.contains(1));
|
|
System.out.println("set.contains(9) = " + set.contains(9));
|
|
System.out.println("set.size() = " + set.size());
|
|
}
|
|
}
|