diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index 27b1c85..0000000
--- a/.gitattributes
+++ /dev/null
@@ -1,2 +0,0 @@
-./java22/*.snippet linguist-detectable=false
-*.snippet linguist-language=Java
\ No newline at end of file
diff --git a/.github/tools/pom.xml b/.github/tools/pom.xml
new file mode 100644
index 0000000..4574d9b
--- /dev/null
+++ b/.github/tools/pom.xml
@@ -0,0 +1,69 @@
+
+
+ 4.0.0
+ tools
+ 1.0.0
+ dev.playground
+
+
+ UTF-8
+ 21
+ 21
+ dev.playground.tools.IndexJson
+ 5.9.2
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ ${junit.version}
+ compile
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ ${junit.version}
+ compile
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ ${junit.version}
+ compile
+
+
+
+
+
+
+ maven-jar-plugin
+ 3.0.2
+
+
+
+ true
+ ${mainClass}
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.11.0
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.22.1
+
+
+
+
diff --git a/.github/tools/src/main/java/dev/playground/tools/IndexJson.java b/.github/tools/src/main/java/dev/playground/tools/IndexJson.java
new file mode 100644
index 0000000..7e6d107
--- /dev/null
+++ b/.github/tools/src/main/java/dev/playground/tools/IndexJson.java
@@ -0,0 +1,43 @@
+package dev.playground.tools;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.stream.Collectors;
+
+public class IndexJson {
+
+ static final String rawGithubCDNPrefix = "https://raw.githubusercontent.com/java/playground-snippets/main/";
+
+ public static void main(String[] args) throws IOException {
+ if (args.length < 1) {
+ System.err.println("USAGE:\n\t[program] ");
+ System.exit(1);
+ }
+ var strPath = args[0];
+ var path = Path.of(strPath);
+ if (!path.toFile().exists()) {
+ System.err.printf("Directory %s does not exist!\nUSAGE:\n\t[program] \n", path);
+ System.exit(1);
+ }
+
+ String result;
+ try(var walker = Files.walk(path)) {
+ result = walker.filter(f -> !Files.isDirectory(f)).map(key -> {
+ var strKey = key.toString().replace(strPath + "/", "");
+ var strValue = rawGithubCDNPrefix + strKey;
+
+ return String.format("\t\"%s\": \"%s\"", strKey, strValue);
+ }).collect(Collectors.joining(",\n"));
+ }
+ var indexJsonContent = String.format("{\n%s\n}", result);
+ var indexJsonFilePath = Path.of(strPath, "index.json");
+ System.out.println(indexJsonFilePath);
+ Files.deleteIfExists(indexJsonFilePath);
+ indexJsonFilePath.toFile().createNewFile();
+
+ Files.writeString(indexJsonFilePath, indexJsonContent);
+ System.out.println(indexJsonContent);
+ }
+}
diff --git a/.github/tools/src/main/resources/README.md b/.github/tools/src/main/resources/README.md
new file mode 100644
index 0000000..9d4fa1c
--- /dev/null
+++ b/.github/tools/src/main/resources/README.md
@@ -0,0 +1,4 @@
+# DISCLAIMER
+
+
+[snippets](snippets) is a symlink to a [root folder](../../../../../snippets).
diff --git a/.github/tools/src/main/resources/snippets b/.github/tools/src/main/resources/snippets
new file mode 120000
index 0000000..80cc2ec
--- /dev/null
+++ b/.github/tools/src/main/resources/snippets
@@ -0,0 +1 @@
+../../../../../snippets
\ No newline at end of file
diff --git a/.github/tools/src/test/java/dev/playground/SnippetTest.java b/.github/tools/src/test/java/dev/playground/SnippetTest.java
new file mode 100644
index 0000000..ce19c31
--- /dev/null
+++ b/.github/tools/src/test/java/dev/playground/SnippetTest.java
@@ -0,0 +1,102 @@
+package dev.playground;
+
+import dev.playground.tools.IndexJson;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.Base64;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.Executors;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class SnippetTest {
+
+ static final HttpRequest.Builder builder = HttpRequest.newBuilder()
+ .version(HttpClient.Version.HTTP_1_1)
+ .headers("Content-Type", "application/x-www-form-urlencoded");
+
+ static final HttpClient client = HttpClient.newBuilder()
+ .connectTimeout(Duration.ofSeconds(300))
+ .version(HttpClient.Version.HTTP_1_1)
+ .executor(Executors.newVirtualThreadPerTaskExecutor())
+ .build();
+
+ static final String bodyTemplate = """
+ {
+ "snippet": "%s",
+ "option": "na"
+ }
+ """;
+
+ static List getData() throws URISyntaxException {
+ List data;
+ var mainClassLoader = IndexJson.class.getClassLoader();
+ var samplesFolder = Path.of(Objects.requireNonNull(mainClassLoader.getResource("snippets")).toURI());
+ try(var files = Files.walk(samplesFolder)) {
+ data = files.filter(fl -> fl.toString().endsWith(".snippet")).map(f -> {
+ String snippet;
+ var snippetPath = f.getParent() + "/" + f.getFileName();
+ try {
+ snippet = new String(Files.readAllBytes(Path.of(snippetPath)));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return snippet;
+ }).toList();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return data;
+ }
+
+ String executeSnippet(String snippet) throws Exception{
+ var publicEndpoint = System.getProperty("execution.endpoint");
+ Assumptions.assumeTrue(Objects.nonNull(publicEndpoint));
+ var requestBody = bodyTemplate.formatted(
+ new String(Base64.getEncoder().encode(snippet.getBytes(StandardCharsets.UTF_8))
+ ));
+ var request = builder.uri(new URI(publicEndpoint))
+ .POST(HttpRequest.BodyPublishers.ofString(requestBody))
+ .build();
+ var response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
+ var responseBody = new String(response.body());
+ assertEquals(200, response.statusCode(), responseBody);
+
+ assertTrue(responseBody.contains("VALID"), responseBody);
+
+
+ return responseBody;
+ }
+
+ @ParameterizedTest
+ @MethodSource(value = "getData")
+ public void testCompile(String snippet) throws Exception {
+ System.out.printf("[SnippetTest::testCompile] Running validation test for snippet:\n%s\n", snippet);
+ executeSnippet(snippet);
+ }
+
+ @Test
+ public void testCharset() throws Exception {
+ var snippet = """
+ System.out.println("tu dois faire ça");
+ """;
+ System.out.printf("[SnippetTest::testCharset] Running charset validation test for snippet:\n%s\n", snippet);
+ var responseBody = executeSnippet(snippet);
+ assertTrue(responseBody.contains("tu dois faire ça"));
+ assertFalse(responseBody.contains("tu dois faire ?a"));
+ }
+}
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..f17d9f0
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,28 @@
+name: build and test
+
+on:
+ pull_request:
+ branches: [ main ]
+
+jobs:
+ build-and-test:
+ runs-on: ubuntu-latest
+ steps:
+ - name: 'Download JDK'
+ id: jdk
+ uses: oracle-actions/setup-java@v1
+ with:
+ website: oracle.com
+ release: 21
+
+ - name: 'Check out repository'
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 1
+
+ - name: run tests
+ shell: bash
+ working-directory: .github/tools
+ run: |
+ mvn test -Dexecution.endpoint=https://i67ddx34g3dcytoxovnbl45u6m.apigateway.us-ashburn-1.oci.customer-oci.com/api/execute
+
diff --git a/.gitignore b/.gitignore
index 524f096..9f6e049 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,24 +1,14 @@
-# Compiled class file
-*.class
+target
+.terraform
+*hcl
+*terraform.tfvars
+*.tfstate*
+__pycache__
+*.tfvars
+.idea
-# Log file
-*.log
+*.local_development*
+input*/
+output*/
-# BlueJ files
-*.ctxt
-# Mobile Tools for Java (J2ME)
-.mtj.tmp/
-
-# Package Files #
-*.jar
-*.war
-*.nar
-*.ear
-*.zip
-*.tar.gz
-*.rar
-
-# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
-hs_err_pid*
-replay_pid*
diff --git a/LICENSE.md b/LICENSE.md
deleted file mode 100644
index de597c5..0000000
--- a/LICENSE.md
+++ /dev/null
@@ -1,10 +0,0 @@
-DISCLAIMER
-
-These are free and unencumbered sample snippets released into the public domain.
-
-Anyone is free to copy, modify, publish, use, compile, sell, or distribute these sample snippets, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
-
-In jurisdictions that recognize copyright laws, the author or authors of these sample snippets dedicate any and all copyright interest in the sample snippets to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to these sample snippets under copyright law.
-
-THE SAMPLE SNIPPETS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SAMPLE SNIPPETS OR THE USE OR OTHER DEALINGS IN THE SAMPLE SNIPPETS.
-
diff --git a/README.md b/README.md
deleted file mode 100644
index f28b740..0000000
--- a/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-# playground-snippets
-
-This repository hosts the samples snippets of the [Java Playground](https://dev.java/playground/).
-
-We don't accept external contributions on this repo. For suggestions and pontential issues, please use [github.com/java/devrel](https://github.com/java/).
diff --git a/java21/HelloWorld.snippet b/java21/HelloWorld.snippet
deleted file mode 100644
index 537e9a3..0000000
--- a/java21/HelloWorld.snippet
+++ /dev/null
@@ -1,2 +0,0 @@
-var version = Runtime.version().feature();
-println("👋 Hello, Java " + version);
diff --git a/java21/Textblock_2.snippet b/java21/Textblock_2.snippet
deleted file mode 100644
index facc1e6..0000000
--- a/java21/Textblock_2.snippet
+++ /dev/null
@@ -1,12 +0,0 @@
-// Text block to stream
-var cities = """
- San Francisco
- Casablanca
- Antwerp
- New Delhi
- Osaka
-""";
-
-Stream lines = cities.lines();
-
-System.out.println(lines.toList());
diff --git a/java22/Gatherers_1.snippet b/java22/Gatherers_1.snippet
deleted file mode 100644
index d176eb2..0000000
--- a/java22/Gatherers_1.snippet
+++ /dev/null
@@ -1,8 +0,0 @@
-// Simple Fixed Window Gatherer
-var strings = List.of("one", "two", "three", "four", "five");
-Gatherer> fixedWindow =
- Gatherers.windowFixed(2);
-var result = strings.stream()
- .gather(fixedWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/Gatherers_2.snippet b/java22/Gatherers_2.snippet
deleted file mode 100644
index 9ce281e..0000000
--- a/java22/Gatherers_2.snippet
+++ /dev/null
@@ -1,8 +0,0 @@
-// Simple Sliding Window Gatherer
-var strings = List.of("one", "two", "three", "four", "five");
-Gatherer> slidingWindow =
- Gatherers.windowSliding(2);
-var result = strings.stream()
- .gather(slidingWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/Gatherers_3.snippet b/java22/Gatherers_3.snippet
deleted file mode 100644
index a911ebe..0000000
--- a/java22/Gatherers_3.snippet
+++ /dev/null
@@ -1,9 +0,0 @@
-// Summing the sliding windows
-var strings = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
-Gatherer> createSlidingWindows =
- Gatherers.windowSliding(2);
-var result = strings.stream()
- .gather(createSlidingWindows)
- .map(windows -> windows.stream().mapToInt(i -> i).sum())
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/Gatherers_4.snippet b/java22/Gatherers_4.snippet
deleted file mode 100644
index 286563d..0000000
--- a/java22/Gatherers_4.snippet
+++ /dev/null
@@ -1,11 +0,0 @@
-// Summing the sliding windows with gatherers
-var strings = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
-Gatherer> createSlidingWindows =
- Gatherers.windowSliding(2);
-Gatherer, ?, Integer> sumEachWindow =
- Gatherer.of((_, list, downstream) -> downstream.push(list.stream().mapToInt(n -> n).sum()));
-var result = strings.stream()
- .gather(createSlidingWindows)
- .gather(sumEachWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/Gatherers_5.snippet b/java22/Gatherers_5.snippet
deleted file mode 100644
index 8df9bb5..0000000
--- a/java22/Gatherers_5.snippet
+++ /dev/null
@@ -1,12 +0,0 @@
-// Composing gatherers
-var strings = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
-Gatherer> createSlidingWindows =
- Gatherers.windowSliding(2);
-Gatherer, ?, Integer> sumEachWindow =
- Gatherer.of((_, list, downstream) -> downstream.push(list.stream().mapToInt(n -> n).sum()));
-Gatherer slideThenSum =
- createSlidingWindows.andThen(sumEachWindow);
-var result = strings.stream()
- .gather(slideThenSum)
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/Gatherers_6.snippet b/java22/Gatherers_6.snippet
deleted file mode 100644
index 7055790..0000000
--- a/java22/Gatherers_6.snippet
+++ /dev/null
@@ -1,18 +0,0 @@
-// Composing gatherers to remove noise
-var strings = List.of(5, 5, 5, 1, 5, 5, 5, 1, 5, 5, 1, 5);
-Gatherer> slide =
- Gatherers.windowSliding(3);
-Gatherer, ?, List> smooth =
- Gatherer.of((_, list, downstream) -> {
- int max = list.stream().mapToInt(n -> n).max().orElseThrow();
- list = List.of(max, max, max);
- return downstream.push(list);
- });
-Gatherer, ?, Integer> unslide =
- Gatherer.of((_, list, downStream) -> downStream.push(list.getFirst()));
-Gatherer smoothOnASlidingWindow =
- slide.andThen(smooth).andThen(unslide);
-var result = strings.stream()
- .gather(smoothOnASlidingWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/StatementsBeforeSuper_1.snippet b/java22/StatementsBeforeSuper_1.snippet
deleted file mode 100644
index 91e1678..0000000
--- a/java22/StatementsBeforeSuper_1.snippet
+++ /dev/null
@@ -1,34 +0,0 @@
-// Statement before super
-static class Shape {
- private String name;
- public Shape(String name) {
- if (name == null) {
- throw new IllegalArgumentException("User should not be null");
- }
- super();
- this.name = name;
- }
- public String name() {
- return name;
- }
-}
-
-static class Square extends Shape {
- private int edge;
- public Square(int edge) {
- if (edge <= 0) {
- throw new IllegalArgumentException("Edge should be greater than 0");
- }
- super("Square");
- this.edge = edge;
- }
- public int edge() {
- return edge;
- }
- public String toString() {
- return "Square[" + edge + "]";
- }
-}
-
-Square square = new Square(100);
-System.out.println("square = " + square);
diff --git a/java22/String_template_1.snippet b/java22/String_template_1.snippet
deleted file mode 100644
index aa74d02..0000000
--- a/java22/String_template_1.snippet
+++ /dev/null
@@ -1,14 +0,0 @@
-// Simple JSON generation with STR
-record Point(int x, int y) {
- public String toJson() {
- return STR."""
- {"x":"\{this.x}", "y":"\{this.y}"}\
- """;
- }
-}
-
-var objects =
- List.of(new Point(1, 1), new Point(2, 2));
-objects.stream()
- .map(Point::toJson)
- .forEach(System.out::println);
diff --git a/java22/String_template_2.snippet b/java22/String_template_2.snippet
deleted file mode 100644
index 89de523..0000000
--- a/java22/String_template_2.snippet
+++ /dev/null
@@ -1,23 +0,0 @@
-// JSON generation with STR and pattern matching
-sealed interface JSonAble permits Point, Circle {}
-record Point(int x, int y) implements JSonAble {}
-record Circle(Point center, int radius) implements JSonAble {}
-public static String jsonOf(JSonAble jSonAble) {
- return switch (jSonAble) {
- case Point(int x, int y) ->
- STR."""
- {"x":"\{x}", "y":"\{y}"}""";
- case Circle(var center, int radius) ->
- STR."""
- {
- "center":"\{jsonOf(center)}",
- "radius":"\{radius}"
- }""";
- };
-}
-
-var objects =
- List.of(
- new Point(1, 1),
- new Circle(new Point(1, 2), 3));
-objects.forEach(element -> System.out.println(jsonOf(element)));
diff --git a/java22/String_template_3.snippet b/java22/String_template_3.snippet
deleted file mode 100644
index c63f784..0000000
--- a/java22/String_template_3.snippet
+++ /dev/null
@@ -1,22 +0,0 @@
-// Printing numbers with FMT
-import static java.util.FormatProcessor.FMT;
-record Price(int price) {}
-record Product(String name, Price price) {
- Product(String name, int price) {
- this(name, new Price(price));
- }
-}
-public static String format(Product product) {
- return FMT."%-6s\{product.name()} %3d\{product.price().price()}";
-}
-
-var products = List.of(
- new Product("Spoon", 5),
- new Product("Fork", 7),
- new Product("Knife", 8),
- new Product("Plate", 12),
- new Product("Glass", 10)
-);
-products.stream()
- .map(product -> format(product))
- .forEach(System.out::println);
diff --git a/java22/String_template_4.snippet b/java22/String_template_4.snippet
deleted file mode 100644
index db7224d..0000000
--- a/java22/String_template_4.snippet
+++ /dev/null
@@ -1,31 +0,0 @@
-// Printing dates with FMT
-import java.time.LocalDate;
-import java.time.format.DateTimeFormatter;
-import static java.util.FormatProcessor.FMT;
-record Price(int price) {}
-record Rental(LocalDate start, LocalDate end, Price price) {
- Rental(String start, String end, int price) {
- this(
- LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE),
- LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE),
- new Price(price));
- }
-}
-public static String format(Rental rental) {
- var formatter = DateTimeFormatter.ofPattern("MMMM dd yyyy");
- return FMT."""
- Rental from \{formatter.format(rental.start())}\
- to \{formatter.format(rental.start())}, \
- for the price \{rental.price().price()}""";
-}
-String format = "MMMM dd yyyy";
-LocalDate today = LocalDate.now();
-System.out.println(DateTimeFormatter.ofPattern("MMMM dd yyyy").format(today));
-var rentals = List.of(
- new Rental("2024-03-19", "2024-03-22", 800),
- new Rental("2024-07-01", "2024-07-31", 4_000),
- new Rental("2024-09-15", "2024-09-22", 2_500)
-);
-rentals.stream()
- .map(rental -> format(rental))
- .forEach(System.out::println);
diff --git a/java22/String_template_5.snippet b/java22/String_template_5.snippet
deleted file mode 100644
index 922a2aa..0000000
--- a/java22/String_template_5.snippet
+++ /dev/null
@@ -1,21 +0,0 @@
-// Simple custom String Template
-Function super StringTemplate, String> function =
- template -> {
- var fragments = template.fragments();
- var values = template.values();
- return IntStream.range(0, fragments.size())
- .boxed()
- .mapMulti((index, downstream) -> {
- downstream.accept(fragments.get(index));
- if (index < values.size()) {
- downstream.accept((String) values.get(index));
- }
- })
- .collect(Collectors.joining());
- };
-var SIMPLE_PRINT = StringTemplate.Processor.of(function);
-var strings = List.of("2023-03-19", "2023-09-23");
-var result1 = SIMPLE_PRINT."\{strings.get(0)}";
-System.out.println("Result 1 = " + result1);
-var result2 = SIMPLE_PRINT."\{strings.get(0)} \{strings.get(1)}";
-System.out.println("Result 2 = " + result2);
diff --git a/java22/String_template_6.snippet b/java22/String_template_6.snippet
deleted file mode 100644
index 0dc767e..0000000
--- a/java22/String_template_6.snippet
+++ /dev/null
@@ -1,30 +0,0 @@
-// Custom string template to analyze CSV
-import java.time.LocalDate;
-import java.time.format.DateTimeFormatter;
-record Price(int price) {
- public static Price of(String price) {
- return new Price(Integer.parseInt(price));
- }
-}
-record Rental(LocalDate start, LocalDate end, Price price) {}
-Function super StringTemplate, Rental> function =
- template -> {
- var values = template.values();
- var start = LocalDate.parse((String) values.get(0), DateTimeFormatter.ISO_LOCAL_DATE);
- var end = LocalDate.parse((String) values.get(1), DateTimeFormatter.ISO_LOCAL_DATE);
- var price = Price.of((String) values.get(2));
- return new Rental(start, end, price);
- };
-var RENTALS = StringTemplate.Processor.of(function);
-var csv = """
- 2023-03-19;2023-03-24;500
- 2023-07-14;2023-07-21;700
- 2023-09-20;2023-09-23;300
- """;
-var splitter = Pattern.compile(";");
-var result = csv.lines()
- .map(splitter::splitAsStream)
- .map(Stream::toList)
- .map(list -> RENTALS."\{list.get(0)} \{list.get(1)} \{list.get(2)}")
- .toList();
-result.forEach(System.out::println);
diff --git a/java22/Switch_on_Sealled_Types_1.snippet b/java22/Switch_on_Sealled_Types_1.snippet
deleted file mode 100644
index 1248584..0000000
--- a/java22/Switch_on_Sealled_Types_1.snippet
+++ /dev/null
@@ -1,48 +0,0 @@
-// Switch on Sealed Types
-sealed interface Shape permits Rectangle, Square, Circle {}
-record Point(double x, double y) {}
-record Edge(double u, double v) {
- public double scalar(Edge other) {
- return this.u*other.u + this.v*other.v;
- }
- public double norm() {
- return Math.sqrt(this.scalar(this));
- }
-}
-record Square(Point p, Edge e) implements Shape {}
-record Rectangle(Point p, Edge e1, Edge e2) implements Shape {
- public Rectangle {
- if (Math.abs(e1.scalar(e2)) > 1E-06)
- throw new IllegalArgumentException("Edges must be orthogonal");
- }
-}
-record Circle(Point center, double radius) implements Shape {}
-
-ToDoubleFunction surface = shape ->
- switch (shape) {
- case Rectangle r -> Math.sqrt(r.e1().norm()*r.e2().norm());
- case Square s -> s.e().norm();
- case Circle c -> Math.PI * c.radius() * c.radius();
- };
-Function toString = shape ->
- switch (shape) {
- case Rectangle r -> "Rectangle -> %.2f".formatted(surface.applyAsDouble(r));
- case Square s -> "Square -> %.2f".formatted(surface.applyAsDouble(s));
- case Circle c -> "Circle -> %.2f".formatted(surface.applyAsDouble(c));
- };
-
-Shape s0 = new Square(new Point(0d, 0d), new Edge(0d, 0d));
-Shape s1 = new Square(new Point(0d, 1d), new Edge(1d, 0d));
-Shape s2 = new Square(new Point(2d, 3d), new Edge(1d, 1d));
-Shape s3 = new Square(new Point(5d, 0d), new Edge(1d, 2d));
-Rectangle r0 = new Rectangle(new Point(0d, 0d), new Edge(0d, 0d), new Edge(0d, 0d));
-Rectangle r1 = new Rectangle(new Point(1d, 2d), new Edge(1d, 0d), new Edge(0d, 0d));
-Rectangle r2 = new Rectangle(new Point(4d, 1d), new Edge(0d, 0d), new Edge(1d, 0d));
-Rectangle r3 = new Rectangle(new Point(0d, 3d), new Edge(1d, 0d), new Edge(0d, 1d));
-Rectangle r4 = new Rectangle(new Point(2d, 3d), new Edge(1d, 1d), new Edge(1d, -1d));
-Circle c1 = new Circle(new Point(0d, 0d), 1d);
-Circle c2 = new Circle(new Point(2d, 3d), 2d);
-var shapes = List.of(s0, s1, s2, s3, r0, r1, r2, r3, r4, c1, c2);
-shapes.stream()
- .map(toString)
- .forEach(System.out::println);
diff --git a/java22/Switch_on_Sealled_Types_2.snippet b/java22/Switch_on_Sealled_Types_2.snippet
deleted file mode 100644
index 3c9c453..0000000
--- a/java22/Switch_on_Sealled_Types_2.snippet
+++ /dev/null
@@ -1,49 +0,0 @@
-// Switch on Sealed Types with Record Patterns
-sealed interface Shape permits Rectangle, Square, Circle {}
-record Point(double x, double y) {}
-record Edge(double u, double v) {
- public double scalar(Edge other) {
- return this.u*other.u + this.v*other.v;
- }
- public double norm() {
- return Math.sqrt(this.scalar(this));
- }
-}
-record Square(Point p, Edge e) implements Shape {}
-record Rectangle(Point p, Edge e1, Edge e2) implements Shape {
- public Rectangle {
- if (Math.abs(e1.scalar(e2)) > 1E-06)
- throw new IllegalArgumentException("Edges must be orthogonal");
- }
-}
-record Circle(Point center, double radius) implements Shape {}
-
-ToDoubleFunction surface = shape -> {
- return switch (shape) {
- case Rectangle(Point _, Edge e1, Edge e2) -> Math.sqrt(e1.norm() * e2.norm());
- case Square(Point _, Edge e) -> e.norm();
- case Circle(Point _, double radius) -> Math.PI * radius * radius;
- };
-};
-Function toString = shape ->
- switch (shape) {
- case Rectangle r -> "Rectangle -> %.2f".formatted(surface.applyAsDouble(r));
- case Square s -> "Square -> %.2f".formatted(surface.applyAsDouble(s));
- case Circle c -> "Circle -> %.2f".formatted(surface.applyAsDouble(c));
- };
-
-Shape s0 = new Square(new Point(0d, 0d), new Edge(0d, 0d));
-Shape s1 = new Square(new Point(0d, 1d), new Edge(1d, 0d));
-Shape s2 = new Square(new Point(2d, 3d), new Edge(1d, 1d));
-Shape s3 = new Square(new Point(5d, 0d), new Edge(1d, 2d));
-Rectangle r0 = new Rectangle(new Point(0d, 0d), new Edge(0d, 0d), new Edge(0d, 0d));
-Rectangle r1 = new Rectangle(new Point(1d, 2d), new Edge(1d, 0d), new Edge(0d, 0d));
-Rectangle r2 = new Rectangle(new Point(4d, 1d), new Edge(0d, 0d), new Edge(1d, 0d));
-Rectangle r3 = new Rectangle(new Point(0d, 3d), new Edge(1d, 0d), new Edge(0d, 1d));
-Rectangle r4 = new Rectangle(new Point(2d, 3d), new Edge(1d, 1d), new Edge(1d, -1d));
-Circle c1 = new Circle(new Point(0d, 0d), 1d);
-Circle c2 = new Circle(new Point(2d, 3d), 2d);
-var shapes = List.of(s0, s1, s2, s3, r0, r1, r2, r3, r4, c1, c2);
-shapes.stream()
- .map(toString)
- .forEach(System.out::println);
diff --git a/java22/Switch_on_Sealled_Types_3.snippet b/java22/Switch_on_Sealled_Types_3.snippet
deleted file mode 100644
index b108f53..0000000
--- a/java22/Switch_on_Sealled_Types_3.snippet
+++ /dev/null
@@ -1,48 +0,0 @@
-// Switch on Sealed Types with Nested Record Patterns
-sealed interface Shape permits Rectangle, Square, Circle {}
-record Point(double x, double y) {}
-record Edge(double u, double v) {
- public double scalar(Edge other) {
- return this.u*other.u + this.v*other.v;
- }
- public double norm() {
- return Math.sqrt(this.scalar(this));
- }
-}
-record Square(Point anchor, Edge e) implements Shape {}
-record Rectangle(Point anchor, Edge e1, Edge e2) implements Shape {
- public Rectangle {
- if (Math.abs(e1.scalar(e2)) > 1E-06)
- throw new IllegalArgumentException("Edges must be orthogonal");
- }
-}
-
-record Circle(Point center, double radius) implements Shape {}
-
-ToDoubleFunction surface = shape ->
- switch (shape) {
- case Rectangle(Point p, Edge e1, Edge e2) -> Math.sqrt(e1.norm()*e2.norm());
- case Square(Point p, Edge e) -> e.norm();
- case Circle(Point center, double radius) -> Math.PI*radius*radius;
- };
-Function toString = shape ->
- switch (shape) {
- case Rectangle r -> "Rectangle -> %.2f".formatted(surface.applyAsDouble(r));
- case Square s -> "Square -> %.2f".formatted(surface.applyAsDouble(s));
- case Circle c -> "Circle -> %.2f".formatted(surface.applyAsDouble(c));
- };
-Shape s0 = new Square(new Point(0d, 0d), new Edge(0d, 0d));
-Shape s1 = new Square(new Point(0d, 1d), new Edge(1d, 0d));
-Shape s2 = new Square(new Point(2d, 3d), new Edge(1d, 1d));
-Shape s3 = new Square(new Point(5d, 0d), new Edge(1d, 2d));
-Rectangle r0 = new Rectangle(new Point(0d, 0d), new Edge(0d, 0d), new Edge(0d, 0d));
-Rectangle r1 = new Rectangle(new Point(1d, 2d), new Edge(1d, 0d), new Edge(0d, 0d));
-Rectangle r2 = new Rectangle(new Point(4d, 1d), new Edge(0d, 0d), new Edge(1d, 0d));
-Rectangle r3 = new Rectangle(new Point(0d, 3d), new Edge(1d, 0d), new Edge(0d, 1d));
-Rectangle r4 = new Rectangle(new Point(2d, 3d), new Edge(1d, 1d), new Edge(1d, -1d));
-Circle c1 = new Circle(new Point(0d, 0d), 1d);
-Circle c2 = new Circle(new Point(2d, 3d), 2d);
-var shapes = List.of(s0, s1, s2, s3, r0, r1, r2, r3, r4, c1, c2);
-shapes.stream()
- .map(toString)
- .forEach(System.out::println);
diff --git a/java22/Switch_on_Sealled_Types_4.snippet b/java22/Switch_on_Sealled_Types_4.snippet
deleted file mode 100644
index c1a86d7..0000000
--- a/java22/Switch_on_Sealled_Types_4.snippet
+++ /dev/null
@@ -1,46 +0,0 @@
-// Switch on Sealed Types with Unnamed Patterns
-sealed interface Shape permits Rectangle, Square, Circle {}
-record Point(double x, double y) {}
-record Edge(double u, double v) {
- public double scalar(Edge other) {
- return this.u*other.u + this.v*other.v;
- }
- public double norm() {
- return Math.sqrt(this.scalar(this));
- }
-}
-record Square(Point anchor, Edge e) implements Shape {}
-record Rectangle(Point anchor, Edge e1, Edge e2) implements Shape {
- public Rectangle {
- if (Math.abs(e1.scalar(e2)) > 1E-06)
- throw new IllegalArgumentException("Edges must be orthogonal");
- }
-}
-record Circle(Point center, double radius) implements Shape {}
-ToDoubleFunction surface = shape ->
- switch (shape) {
- case Rectangle(_, var e1, var e2) -> Math.sqrt(e1.norm()*e2.norm());
- case Square(_, var e) -> e.norm();
- case Circle(_, var radius) -> Math.PI*radius*radius;
- };
-Function toString = shape ->
- switch (shape) {
- case Rectangle r -> "Rectangle -> %.2f".formatted(surface.applyAsDouble(r));
- case Square s -> "Square -> %.2f".formatted(surface.applyAsDouble(s));
- case Circle c -> "Circle -> %.2f".formatted(surface.applyAsDouble(c));
- };
-Shape s0 = new Square(new Point(0d, 0d), new Edge(0d, 0d));
-Shape s1 = new Square(new Point(0d, 1d), new Edge(1d, 0d));
-Shape s2 = new Square(new Point(2d, 3d), new Edge(1d, 1d));
-Shape s3 = new Square(new Point(5d, 0d), new Edge(1d, 2d));
-Rectangle r0 = new Rectangle(new Point(0d, 0d), new Edge(0d, 0d), new Edge(0d, 0d));
-Rectangle r1 = new Rectangle(new Point(1d, 2d), new Edge(1d, 0d), new Edge(0d, 0d));
-Rectangle r2 = new Rectangle(new Point(4d, 1d), new Edge(0d, 0d), new Edge(1d, 0d));
-Rectangle r3 = new Rectangle(new Point(0d, 3d), new Edge(1d, 0d), new Edge(0d, 1d));
-Rectangle r4 = new Rectangle(new Point(2d, 3d), new Edge(1d, 1d), new Edge(1d, -1d));
-Circle c1 = new Circle(new Point(0d, 0d), 1d);
-Circle c2 = new Circle(new Point(2d, 3d), 2d);
-var shapes = List.of(s0, s1, s2, s3, r0, r1, r2, r3, r4, c1, c2);
-shapes.stream()
- .map(toString)
- .forEach(System.out::println);
diff --git a/java22/Switch_on_Sealled_Types_5.snippet b/java22/Switch_on_Sealled_Types_5.snippet
deleted file mode 100644
index 780e909..0000000
--- a/java22/Switch_on_Sealled_Types_5.snippet
+++ /dev/null
@@ -1,55 +0,0 @@
-// Switch on Sealed Types with Guarded Patterns
-sealed interface Shape permits Rectangle, Square, Circle {}
-record Point(double x, double y) {}
-record Edge(double u, double v) {
- public double scalar(Edge other) {
- return this.u*other.u + this.v*other.v;
- }
- public double norm() {
- return Math.sqrt(this.scalar(this));
- }
- public boolean isNull() {
- return this.norm() < 1E-6;
- }
-}
-record Square(Point anchor, Edge e) implements Shape {}
-record Rectangle(Point anchor, Edge e1, Edge e2) implements Shape {
- public Rectangle {
- if (Math.abs(e1.scalar(e2)) > 1E-06)
- throw new IllegalArgumentException("Edges must be orthogonal");
- }
-}
-record Circle(Point center, double radius) implements Shape {}
-ToDoubleFunction surface = shape ->
- switch (shape) {
- case Rectangle(_, var e1, var e2)
- when e1.isNull() || e2.isNull() -> 0d;
- case Rectangle(_, var e1, var e2) -> Math.sqrt(e1.norm()*e2.norm());
- case Square(_, var e)
- when e.isNull() -> 0d;
- case Square(_, var e) -> e.norm();
- case Circle(_, var radius)
- when Math.abs(radius) < 1E-6 -> 0d;
- case Circle(_, var radius) -> Math.PI*radius*radius;
- };
-Function toString = shape ->
- switch (shape) {
- case Rectangle r -> "Rectangle -> %.2f".formatted(surface.applyAsDouble(r));
- case Square s -> "Square -> %.2f".formatted(surface.applyAsDouble(s));
- case Circle c -> "Circle -> %.2f".formatted(surface.applyAsDouble(c));
- };
-Shape s0 = new Square(new Point(0d, 0d), new Edge(0d, 0d));
-Shape s1 = new Square(new Point(0d, 1d), new Edge(1d, 0d));
-Shape s2 = new Square(new Point(2d, 3d), new Edge(1d, 1d));
-Shape s3 = new Square(new Point(5d, 0d), new Edge(1d, 2d));
-Rectangle r0 = new Rectangle(new Point(0d, 0d), new Edge(0d, 0d), new Edge(0d, 0d));
-Rectangle r1 = new Rectangle(new Point(1d, 2d), new Edge(1d, 0d), new Edge(0d, 0d));
-Rectangle r2 = new Rectangle(new Point(4d, 1d), new Edge(0d, 0d), new Edge(1d, 0d));
-Rectangle r3 = new Rectangle(new Point(0d, 3d), new Edge(1d, 0d), new Edge(0d, 1d));
-Rectangle r4 = new Rectangle(new Point(2d, 3d), new Edge(1d, 1d), new Edge(1d, -1d));
-Circle c1 = new Circle(new Point(0d, 0d), 1d);
-Circle c2 = new Circle(new Point(2d, 3d), 2d);
-var shapes = List.of(s0, s1, s2, s3, r0, r1, r2, r3, r4, c1, c2);
-shapes.stream()
- .map(toString)
- .forEach(System.out::println);
diff --git a/java22/Unamed_Pattern_1.snippet b/java22/Unamed_Pattern_1.snippet
deleted file mode 100644
index 476252e..0000000
--- a/java22/Unamed_Pattern_1.snippet
+++ /dev/null
@@ -1,4 +0,0 @@
-// Consumer with Unnamed Pattern
-List strings = List.of("one", "two", "three");
-Consumer notInterested = _ -> System.out.println("I'm not interested in this argument");
-strings.forEach(notInterested);
diff --git a/java22/Unamed_Pattern_2.snippet b/java22/Unamed_Pattern_2.snippet
deleted file mode 100644
index bf3cec3..0000000
--- a/java22/Unamed_Pattern_2.snippet
+++ /dev/null
@@ -1,7 +0,0 @@
-// Function with Unnamed Pattern
-List strings = List.of("1", "11", "111");
-Function constantLength = _ -> 3;
-var result = strings.stream()
- .map(constantLength)
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/Unamed_Pattern_3.snippet b/java22/Unamed_Pattern_3.snippet
deleted file mode 100644
index c89e0dd..0000000
--- a/java22/Unamed_Pattern_3.snippet
+++ /dev/null
@@ -1,7 +0,0 @@
-// BiFunction with Unnamed Pattern
-var strings = List.of("one", "two", "three", "four");
-BiFunction indexer = (_, i) -> i;
-var result = IntStream.range(0, strings.size())
- .mapToObj(index -> indexer.apply(strings.get(index), index))
- .toList();
-System.out.println("result = " + result);
diff --git a/java22/Unamed_Pattern_4.snippet b/java22/Unamed_Pattern_4.snippet
deleted file mode 100644
index a4fd991..0000000
--- a/java22/Unamed_Pattern_4.snippet
+++ /dev/null
@@ -1,49 +0,0 @@
-// Pattern Matching with Unnamed Pattern
-sealed interface Operation permits Add, Mult, Sub, Div {}
-record Add(int left, int right) implements Operation {
- public String toString() {
- return left + " + " + right;
- }
-}
-record Mult(int left, int right) implements Operation {
- public String toString() {
- return left + "*" + right;
- }
-}
-record Sub(int left, int right) implements Operation {
- public String toString() {
- return left + " - " + right;
- }
-}
-record Div(int left, int right) implements Operation {
- public String toString() {
- return left + "/" + right;
- }
-}
-public static boolean naturalNumber(Operation operation) {
- return switch (operation) {
- case Add _ -> true;
- case Mult _ -> true;
- case Sub(int left, int right) -> left > right;
- case Div(int left, int right) -> left % right == 0;
- };
-}
-public static int resolve(Operation operation) {
- return switch(operation) {
- case Add(int left, int right) -> left + right;
- case Mult(int left, int right) -> left * right;
- case Sub(int left, int right) -> left - right;
- case Div(int left, int right) -> left / right;
- };
-}
-
-var operations = List.of(
- new Add(1, 2),
- new Mult(4, 3),
- new Sub(0, 3), new Sub(4, 3),
- new Div(9, 4), new Div(1, 3), new Div(12, 4));
-System.out.println("Are the following natural integers?");
-operations.forEach(operation -> {
- System.out.println(operation + (
- naturalNumber(operation) ? " = " + resolve(operation): " -> result is not a natural integer"));
-});
diff --git a/java23/Gatherers_1.snippet b/java23/Gatherers_1.snippet
deleted file mode 100644
index d176eb2..0000000
--- a/java23/Gatherers_1.snippet
+++ /dev/null
@@ -1,8 +0,0 @@
-// Simple Fixed Window Gatherer
-var strings = List.of("one", "two", "three", "four", "five");
-Gatherer> fixedWindow =
- Gatherers.windowFixed(2);
-var result = strings.stream()
- .gather(fixedWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java23/Gatherers_2.snippet b/java23/Gatherers_2.snippet
deleted file mode 100644
index 9ce281e..0000000
--- a/java23/Gatherers_2.snippet
+++ /dev/null
@@ -1,8 +0,0 @@
-// Simple Sliding Window Gatherer
-var strings = List.of("one", "two", "three", "four", "five");
-Gatherer> slidingWindow =
- Gatherers.windowSliding(2);
-var result = strings.stream()
- .gather(slidingWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java23/Gatherers_3.snippet b/java23/Gatherers_3.snippet
deleted file mode 100644
index a911ebe..0000000
--- a/java23/Gatherers_3.snippet
+++ /dev/null
@@ -1,9 +0,0 @@
-// Summing the sliding windows
-var strings = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
-Gatherer> createSlidingWindows =
- Gatherers.windowSliding(2);
-var result = strings.stream()
- .gather(createSlidingWindows)
- .map(windows -> windows.stream().mapToInt(i -> i).sum())
- .toList();
-System.out.println("result = " + result);
diff --git a/java23/Gatherers_4.snippet b/java23/Gatherers_4.snippet
deleted file mode 100644
index 286563d..0000000
--- a/java23/Gatherers_4.snippet
+++ /dev/null
@@ -1,11 +0,0 @@
-// Summing the sliding windows with gatherers
-var strings = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
-Gatherer> createSlidingWindows =
- Gatherers.windowSliding(2);
-Gatherer, ?, Integer> sumEachWindow =
- Gatherer.of((_, list, downstream) -> downstream.push(list.stream().mapToInt(n -> n).sum()));
-var result = strings.stream()
- .gather(createSlidingWindows)
- .gather(sumEachWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java23/Gatherers_5.snippet b/java23/Gatherers_5.snippet
deleted file mode 100644
index 8df9bb5..0000000
--- a/java23/Gatherers_5.snippet
+++ /dev/null
@@ -1,12 +0,0 @@
-// Composing gatherers
-var strings = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
-Gatherer> createSlidingWindows =
- Gatherers.windowSliding(2);
-Gatherer, ?, Integer> sumEachWindow =
- Gatherer.of((_, list, downstream) -> downstream.push(list.stream().mapToInt(n -> n).sum()));
-Gatherer slideThenSum =
- createSlidingWindows.andThen(sumEachWindow);
-var result = strings.stream()
- .gather(slideThenSum)
- .toList();
-System.out.println("result = " + result);
diff --git a/java23/Gatherers_6.snippet b/java23/Gatherers_6.snippet
deleted file mode 100644
index 7055790..0000000
--- a/java23/Gatherers_6.snippet
+++ /dev/null
@@ -1,18 +0,0 @@
-// Composing gatherers to remove noise
-var strings = List.of(5, 5, 5, 1, 5, 5, 5, 1, 5, 5, 1, 5);
-Gatherer> slide =
- Gatherers.windowSliding(3);
-Gatherer, ?, List> smooth =
- Gatherer.of((_, list, downstream) -> {
- int max = list.stream().mapToInt(n -> n).max().orElseThrow();
- list = List.of(max, max, max);
- return downstream.push(list);
- });
-Gatherer, ?, Integer> unslide =
- Gatherer.of((_, list, downStream) -> downStream.push(list.getFirst()));
-Gatherer smoothOnASlidingWindow =
- slide.andThen(smooth).andThen(unslide);
-var result = strings.stream()
- .gather(smoothOnASlidingWindow)
- .toList();
-System.out.println("result = " + result);
diff --git a/java23/Gatherers_7.snippet b/java23/Gatherers_7.snippet
deleted file mode 100644
index a52b3bf..0000000
--- a/java23/Gatherers_7.snippet
+++ /dev/null
@@ -1,33 +0,0 @@
-// Inserting an element into a stream
-interface GathererSupplier {
- String get();
- default Gatherer at(int insertionIndex) {
- return Gatherer.ofSequential(
- () -> new Object() {
- int index;
- final String element = get();
- },
- (state, s, stream) -> {
- if (state.index != insertionIndex) {
- state.index++;
- return stream.push(s);
- } else {
- stream.push(state.element);
- stream.push(s);
- state.index++;
- return true;
- }
- }
- );
- }
-}
-GathererSupplier insert(String element) {
- return () -> element;
-}
-var ints = List.of("one", "two", "three", "four", "five");
-var index = 3;
-var element = "something";
-var result = ints.stream()
- .gather(insert(element).at(index))
- .toList();
-System.out.println("result = " + result);
diff --git a/java23/Primitive_Type_Pattern_1.snippet b/java23/Primitive_Type_Pattern_1.snippet
deleted file mode 100644
index c4ab06e..0000000
--- a/java23/Primitive_Type_Pattern_1.snippet
+++ /dev/null
@@ -1,26 +0,0 @@
-// Primitive Pattern Matching for InstanceOf
-record JsonDouble(double d) {}
-record JsonFloat(float f) {}
-record JsonLong(long i) {}
-record JsonInt(int i) {}
-
-void analyze(Object o) {
- if (o instanceof JsonDouble(double d)) {
- System.out.println("o is wrapping a double " + d);
- } else if (o instanceof JsonLong(long l)) {
- System.out.println("o is wrapping a long " + l);
- } else if (o instanceof JsonInt(int i)) {
- System.out.println("o is wrapping an int " + i);
- } else {
- System.out.println("Unrecognized wrapper " + o);
- }
-}
-
-var jsonDouble = new JsonDouble(Math.PI);
-analyze(jsonDouble);
-var jsonFloat = new JsonFloat((float)Math.PI);
-analyze(jsonFloat);
-var jsonLong = new JsonLong(314L);
-analyze(jsonLong);
-var jsonInt = new JsonInt(31);
-analyze(jsonInt);
diff --git a/java23/Primitive_Type_Pattern_2.snippet b/java23/Primitive_Type_Pattern_2.snippet
deleted file mode 100644
index 55d807c..0000000
--- a/java23/Primitive_Type_Pattern_2.snippet
+++ /dev/null
@@ -1,25 +0,0 @@
-// Primitive Pattern Matching for Switch
-sealed interface JsonNumber permits
- JsonDouble, JsonFloat, JsonLong, JsonInt {}
-record JsonDouble(double d) implements JsonNumber {}
-record JsonFloat(float f) implements JsonNumber {}
-record JsonLong(long i) implements JsonNumber {}
-record JsonInt(int i) implements JsonNumber {}
-
-void analyze(JsonNumber jsonNumber) {
- switch(jsonNumber) {
- case JsonDouble(double d) -> System.out.println("Double: " + d);
- case JsonFloat(float f) -> System.out.println("Float: " + f);
- case JsonLong(long l) -> System.out.println("Long: " + l);
- case JsonInt(int i) -> System.out.println("Int: " + i);
- }
-}
-
-JsonNumber jsonNumber = new JsonDouble(Math.PI);
-analyze(jsonNumber);
-jsonNumber = new JsonFloat((float)Math.PI);
-analyze(jsonNumber);
-jsonNumber = new JsonLong(314L);
-analyze(jsonNumber);
-jsonNumber = new JsonInt(31);
-analyze(jsonNumber);
diff --git a/java23/Primitive_Type_Pattern_3.snippet b/java23/Primitive_Type_Pattern_3.snippet
deleted file mode 100644
index 33b0a2a..0000000
--- a/java23/Primitive_Type_Pattern_3.snippet
+++ /dev/null
@@ -1,21 +0,0 @@
-// Narrowing Integer Number Primitive Pattern
-sealed interface JsonNumber
- permits JsonLong, JsonInt, JsonChar, JsonByte {}
-record JsonLong(long l) implements JsonNumber {}
-record JsonInt(int i) implements JsonNumber {}
-record JsonChar(char i) implements JsonNumber {}
-record JsonByte(byte i) implements JsonNumber {}
-
-JsonNumber narrow(long number) {
- return switch (number) {
- case byte b -> new JsonByte(b);
- case char c -> new JsonChar(c);
- case int i -> new JsonInt(i);
- case long l -> new JsonLong(l);
- };
-}
-
-System.out.println("Narrowing to byte " + narrow(10L));
-System.out.println("Narrowing to char " + narrow(200L));
-System.out.println("Narrowing to int " + narrow(0x80000));
-System.out.println("Not narrowing " + narrow(0x80000000L));
diff --git a/java23/Primitive_Type_Pattern_4.snippet b/java23/Primitive_Type_Pattern_4.snippet
deleted file mode 100644
index cccb473..0000000
--- a/java23/Primitive_Type_Pattern_4.snippet
+++ /dev/null
@@ -1,16 +0,0 @@
-// Narrowing Floating Point Number Primitive Pattern
-sealed interface JsonNumber
- permits JsonDouble, JsonFloat {}
-record JsonDouble(double d) implements JsonNumber {}
-record JsonFloat(float f) implements JsonNumber {}
-
-JsonNumber narrow(double number) {
- return switch (number) {
- case float f -> new JsonFloat(f);
- case double d -> new JsonDouble(d);
- };
-}
-
-System.out.println("Narrowing to float " + narrow(3.0d));
-System.out.println("Not Narrowing " + narrow(3.14d));
-System.out.println("Not Narrowing " + narrow(Math.PI));
diff --git a/java23/Primitive_Type_Pattern_5.snippet b/java23/Primitive_Type_Pattern_5.snippet
deleted file mode 100644
index 6fc59f9..0000000
--- a/java23/Primitive_Type_Pattern_5.snippet
+++ /dev/null
@@ -1,16 +0,0 @@
-// Integer Number to Floating Point Number Primitive Pattern
-sealed interface JsonNumber
- permits JsonDouble, JsonFloat, JsonInt {}
-record JsonDouble(double d) implements JsonNumber {}
-record JsonFloat(float f) implements JsonNumber {}
-record JsonInt(int i) implements JsonNumber {}
-
-JsonNumber narrow(int number) {
- return switch (number) {
- case float f -> new JsonFloat(f);
- case double d -> new JsonDouble(d);
- };
-}
-
-System.out.println("Int to float: " + narrow(10));
-System.out.println("Int to double: " + narrow(0x1000001));
diff --git a/java23/Primitive_Type_Pattern_6.snippet b/java23/Primitive_Type_Pattern_6.snippet
deleted file mode 100644
index 9262eb5..0000000
--- a/java23/Primitive_Type_Pattern_6.snippet
+++ /dev/null
@@ -1,19 +0,0 @@
-// Floating Point Number to Integer Number Primitive Pattern
-sealed interface JsonNumber
- permits JsonDouble, JsonFloat, JsonInt, JsonByte {}
-record JsonDouble(double d) implements JsonNumber {}
-record JsonFloat(float f) implements JsonNumber {}
-record JsonInt(int i) implements JsonNumber {}
-record JsonByte(byte b) implements JsonNumber {}
-
-JsonNumber narrow(float number) {
- return switch (number) {
- case byte b -> new JsonByte(b);
- case int i -> new JsonInt(i);
- case float f -> new JsonFloat(f);
- };
-}
-
-System.out.println("Float to byte: " + narrow(10f));
-System.out.println("Float to int: " + narrow(1_000f));
-System.out.println("Cant convert: " + narrow(3.14f));
diff --git a/java23/Primitive_Type_Pattern_7.snippet b/java23/Primitive_Type_Pattern_7.snippet
deleted file mode 100644
index 86fc4b2..0000000
--- a/java23/Primitive_Type_Pattern_7.snippet
+++ /dev/null
@@ -1,21 +0,0 @@
-// Double Number to Integer Number Primitive Pattern
-sealed interface JsonNumber
- permits JsonDouble, JsonLong, JsonInt, JsonByte {}
-record JsonDouble(double d) implements JsonNumber {}
-record JsonLong(long l) implements JsonNumber {}
-record JsonInt(int i) implements JsonNumber {}
-record JsonByte(byte b) implements JsonNumber {}
-
-JsonNumber narrow(double number) {
- return switch (number) {
- case byte b -> new JsonByte(b);
- case int i -> new JsonInt(i);
- case long l -> new JsonLong(l);
- case double d -> new JsonDouble(d);
- };
-}
-
-System.out.println("Double to byte: " + narrow(10d));
-System.out.println("Double to int: " + narrow(1_000d));
-System.out.println("Double to long: " + narrow(8_000_000_000d));
-System.out.println("Cant convert: " + narrow(3.14d));
diff --git a/java23/Primitive_Type_Pattern_8.snippet b/java23/Primitive_Type_Pattern_8.snippet
deleted file mode 100644
index 8cbffd0..0000000
--- a/java23/Primitive_Type_Pattern_8.snippet
+++ /dev/null
@@ -1,15 +0,0 @@
-// Boolean Primitive Pattern
-sealed interface JsonBoolean
- permits JsonTrue, JsonFalse {}
-record JsonTrue() implements JsonBoolean {}
-record JsonFalse() implements JsonBoolean {}
-
-JsonBoolean box(boolean value) {
- return switch (value) {
- case true -> new JsonTrue();
- case false -> new JsonFalse();
- };
-}
-
-System.out.println("Boxing true: " + box(true));
-System.out.println("Boxing false: " + box(false));
diff --git a/java23/Primitive_Type_Pattern_9.snippet b/java23/Primitive_Type_Pattern_9.snippet
deleted file mode 100644
index cdda3ed..0000000
--- a/java23/Primitive_Type_Pattern_9.snippet
+++ /dev/null
@@ -1,18 +0,0 @@
-// Double Primitive Pattern
-sealed interface JsonDouble
- permits JsonZero, JsonNegative, JsonPositive {}
-record JsonZero() implements JsonDouble {}
-record JsonPositive() implements JsonDouble {}
-record JsonNegative() implements JsonDouble {}
-
-JsonDouble box(double value) {
- return switch (value) {
- case 0d -> new JsonZero();
- case double v when v > 0d -> new JsonPositive();
- case double v -> new JsonNegative();
- };
-}
-
-System.out.println("Boxing 0d: " + box(0d));
-System.out.println("Boxing 10d: " + box(10d));
-System.out.println("Boxing -10d: " + box(-10d));
diff --git a/java24/Gatherers_A1.snippet b/java24/Gatherers_A1.snippet
deleted file mode 100644
index de50f28..0000000
--- a/java24/Gatherers_A1.snippet
+++ /dev/null
@@ -1,15 +0,0 @@
-// Filtering Gatherer
-var strings = List.of("one", "two", "three", "four", "five");
-Gatherer filtering =
- Gatherer.of(
- (_, element, downstream) -> {
- if (element.length() > 3) {
- return downstream.push(element);
- } else {
- return !downstream.isRejecting();
- }
- });
-var result = strings.stream()
- .gather(filtering)
- .toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_A2.snippet b/java24/Gatherers_A2.snippet
deleted file mode 100644
index eea5534..0000000
--- a/java24/Gatherers_A2.snippet
+++ /dev/null
@@ -1,9 +0,0 @@
-// Mapping Gatherer
-var strings = List.of("one", "two", "three", "four", "five");
-Gatherer mapping =
- Gatherer.of(
- (_, element, downstream) -> downstream.push(element.length()));
-var result = strings.stream()
- .gather(mapping)
- .toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_A3.snippet b/java24/Gatherers_A3.snippet
deleted file mode 100644
index 75beaef..0000000
--- a/java24/Gatherers_A3.snippet
+++ /dev/null
@@ -1,19 +0,0 @@
-// Flatmapping Gatherer
-var strings = List.of("one", "two", "three", "four", "five");
-Gatherer flatMapping =
- Gatherer.of(
- (_, element, downstream) -> {
- var chars = element.toCharArray();
- int index = 0;
- boolean isRejecting = false;
- do {
- isRejecting = !downstream.push(Character.toString(chars[index]));
- index++;
- } while (index < chars.length && !isRejecting);
- return !isRejecting;
- });
-var result = strings.stream()
- .gather(flatMapping)
- .distinct()
- .toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B1.snippet b/java24/Gatherers_B1.snippet
deleted file mode 100644
index f4271df..0000000
--- a/java24/Gatherers_B1.snippet
+++ /dev/null
@@ -1,21 +0,0 @@
-// Map Filter Gatherer
-static Gatherer mapFilter(
- Function super T, ? extends R> mapper,
- Predicate super R> filter) {
-
- return Gatherer.of(
- (_, element, downstream) -> {
- R mappedElement = mapper.apply(element);
- if (filter.test(mappedElement)) {
- return downstream.push(mappedElement);
- }
- return true;
- }
- );
-}
-
-var stream = Stream.of("one", "two", "three", "four", "five");
-var result = stream
- .gather(mapFilter(String::length, length -> length > 3))
- .toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B10.snippet b/java24/Gatherers_B10.snippet
deleted file mode 100644
index 35e761f..0000000
--- a/java24/Gatherers_B10.snippet
+++ /dev/null
@@ -1,28 +0,0 @@
-// Sort Distinct Parallel Gatherer
-static Gatherer sortDistinctWithComparator(Comparator super T> comparator) {
-
- return Gatherer.of(
- () -> new TreeSet(comparator),
- (list, element, _) -> {
- list.add(element);
- return true;
- },
- (set1, set2) -> {
- set1.addAll(set2);
- return set1;
- },
- (list, downstream) -> {
- list.stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-static > Gatherer sortDistinct() {
- return sortDistinctWithComparator(Comparator.naturalOrder());
-}
-
-var stream = Stream.of(3, 2, 4, 5, 3, 1, 2, 5, 4);
-var result = stream.parallel().gather(sortDistinct()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B11.snippet b/java24/Gatherers_B11.snippet
deleted file mode 100644
index cce269e..0000000
--- a/java24/Gatherers_B11.snippet
+++ /dev/null
@@ -1,17 +0,0 @@
-// Distinct Ignore Case Gatherer
-static Gatherer distinctIgnoreCase() {
-
- return Gatherer.ofSequential(
- () -> new HashSet(),
- (set, element, downstream) -> {
- if (set.add(element.toLowerCase())) {
- return downstream.push(element);
- }
- return true;
- }
- );
-}
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo");
-var result = stream.gather(distinctIgnoreCase()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B12.snippet b/java24/Gatherers_B12.snippet
deleted file mode 100644
index f8f0e7f..0000000
--- a/java24/Gatherers_B12.snippet
+++ /dev/null
@@ -1,24 +0,0 @@
-// Distinct Ignore Case Parallel Gatherer
-static Gatherer distinctIgnoreCase() {
-
- return Gatherer.of(
- () -> new HashMap(),
- (map, element, _) -> {
- map.putIfAbsent(element.toLowerCase(), element);
- return true;
- },
- (map1, map2) -> {
- map2.putAll(map1);
- return map2;
- },
- (map, downstream) -> {
- map.values().stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo");
-var result = stream.parallel().gather(distinctIgnoreCase()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B13.snippet b/java24/Gatherers_B13.snippet
deleted file mode 100644
index a360caf..0000000
--- a/java24/Gatherers_B13.snippet
+++ /dev/null
@@ -1,23 +0,0 @@
-// Distinct Ignore Case With Comparator Gatherer
-static Gatherer distinctIgnoreCase() {
-
- return Gatherer.ofSequential(
- () -> new HashMap(),
- (map, element, _) -> {
- map.merge(
- element.toLowerCase(),
- element,
- (e1, e2) -> e1.compareTo(e2) < 0 ? e1 : e2);
- return true;
- },
- (map, downstream) -> {
- map.values().stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo");
-var result = stream.gather(distinctIgnoreCase()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B14.snippet b/java24/Gatherers_B14.snippet
deleted file mode 100644
index 495fb95..0000000
--- a/java24/Gatherers_B14.snippet
+++ /dev/null
@@ -1,32 +0,0 @@
-// Distinct Ignore Case With Comparator Parallel Gatherer
-static Gatherer distinctIgnoreCase() {
-
- return Gatherer.of(
- () -> new HashMap(),
- (map, element, _) -> {
- map.merge(
- element.toLowerCase(),
- element,
- (e1, e2) -> e1.compareTo(e2) < 0 ? e1 : e2);
- return true;
- },
- (map1, map2) -> {
- map2.forEach((key, value) ->
- map1.merge(
- key,
- value,
- (e1, e2) -> e1.compareTo(e2) < 0 ? e1 : e2));
- return map1;
- },
- (map, downstream) -> {
- map.values().stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo");
-var result = stream.parallel().gather(distinctIgnoreCase()).toList();
-System.out.println("result = " + result);
-
diff --git a/java24/Gatherers_B15.snippet b/java24/Gatherers_B15.snippet
deleted file mode 100644
index 1591f01..0000000
--- a/java24/Gatherers_B15.snippet
+++ /dev/null
@@ -1,21 +0,0 @@
-// Custom Equal Gatherer
-static Gatherer customEqual(Function super T, ? extends R> equalMapper) {
-
- return Gatherer.ofSequential(
- () -> new HashMap(),
- (map, element, _) -> {
- var key = equalMapper.apply(element);
- map.putIfAbsent(key, element);
- return true;
- },
- (map, downstream) -> {
- map.values().stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo");
-var result = stream.gather(customEqual(String::toLowerCase)).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B16.snippet b/java24/Gatherers_B16.snippet
deleted file mode 100644
index 246c5b2..0000000
--- a/java24/Gatherers_B16.snippet
+++ /dev/null
@@ -1,25 +0,0 @@
-// Custom Equal Parallel Gatherer
-static Gatherer customEqual(Function super T, ? extends R> equalMapper) {
-
- return Gatherer.of(
- () -> new HashMap(),
- (map, element, _) -> {
- var key = equalMapper.apply(element);
- map.putIfAbsent(key, element);
- return true;
- },
- (map1, map2) -> {
- map2.forEach(map1::putIfAbsent);
- return map1;
- },
- (map, downstream) -> {
- map.values().stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo");
-var result = stream.parallel().gather(customEqual(String::toLowerCase)).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B17.snippet b/java24/Gatherers_B17.snippet
deleted file mode 100644
index c58b416..0000000
--- a/java24/Gatherers_B17.snippet
+++ /dev/null
@@ -1,29 +0,0 @@
-// Custom Equal Collecting Gatherer
-static Gatherer customEqualCollecting(
- Function super T, ? extends R> equalMapper,
- Collector super T, ?, ? extends RR> collector) {
-
- return Gatherer.ofSequential(
- () -> new HashMap>(),
- (map, element, _) -> {
- var key = equalMapper.apply(element);
- map.computeIfAbsent(key, _ -> new ArrayList<>()).add(element);
- return true;
- },
- (map, downstream) -> {
- map.values().stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .map(values -> values.stream().collect(collector))
- .forEach(downstream::push);
- }
- );
-}
-
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo", "Three", "three");
-var result =
- stream
- .gather(
- customEqualCollecting(String::toLowerCase, Collectors.toList()))
- .toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B18.snippet b/java24/Gatherers_B18.snippet
deleted file mode 100644
index 7d847be..0000000
--- a/java24/Gatherers_B18.snippet
+++ /dev/null
@@ -1,28 +0,0 @@
-// Custom Equal Collecting Parallel Gatherer
-static Gatherer customEqualCollecting(
- Function super T, ? extends R> equalMapper,
- Collector super T, ?, ? extends RR> collector) {
-
-return Gatherer.of(
- () -> new HashMap>(),
- (map, element, _) -> {
- var key = equalMapper.apply(element);
- map.computeIfAbsent(key, _ -> new ArrayList<>()).add(element);
- return true;
- },
- (map1, map2) -> {
- map2.forEach((key, value) -> map1.merge(key, value, (v1, v2) -> { v1.addAll(v2); return v1; }));
- return map1;
- },
- (map, downstream) -> {
- map.values().stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .map(values -> values.stream().collect(collector))
- .forEach(downstream::push);
- }
- );
-}
-
-var stream = Stream.of("one", "One", "ONE", "Two", "two", "tWo", "Three", "three");
-var result = stream.gather(customEqualCollecting(String::toLowerCase, Collectors.toList())).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B2.snippet b/java24/Gatherers_B2.snippet
deleted file mode 100644
index 24b65c4..0000000
--- a/java24/Gatherers_B2.snippet
+++ /dev/null
@@ -1,21 +0,0 @@
-// Map Filter Parallel Gatherer
-static Gatherer mapFilter(
- Function super T, ? extends R> mapper,
- Predicate super R> filter) {
-
- return Gatherer.of(
- (_, element, downstream) -> {
- R mappedElement = mapper.apply(element);
- if (filter.test(mappedElement)) {
- return downstream.push(mappedElement);
- }
- return true;
- }
- );
-}
-
-var stream = Stream.of("one", "two", "three", "four", "five");
-var result = stream.parallel()
- .gather(mapFilter(String::length, length -> length > 3))
- .toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B3.snippet b/java24/Gatherers_B3.snippet
deleted file mode 100644
index ab1c3f6..0000000
--- a/java24/Gatherers_B3.snippet
+++ /dev/null
@@ -1,20 +0,0 @@
-// Limit Gatherer
-static Gatherer limit(long limit) {
- return Gatherer.ofSequential(
- () -> new Object() {
- long counter = 0L;
- },
- (counter, element, downstream) -> {
- if (counter.counter >= limit) {
- return false;
- } else {
- counter.counter++;
- return downstream.push(element);
- }
- }
- );
-}
-
-var stream = Stream.of(1, 2, 3, 4, 5);
-var result = stream.gather(limit(3L)).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B4.snippet b/java24/Gatherers_B4.snippet
deleted file mode 100644
index 858d592..0000000
--- a/java24/Gatherers_B4.snippet
+++ /dev/null
@@ -1,20 +0,0 @@
-// Limit Parallel Gatherer
-static Gatherer limit(long limit) {
- return Gatherer.ofSequential(
- () -> new Object() {
- long counter = 0L;
- },
- (counter, element, downstream) -> {
- if (counter.counter >= limit) {
- return false;
- } else {
- counter.counter++;
- return downstream.push(element);
- }
- }
- );
-}
-
-var stream = Stream.of(1, 2, 3, 4, 5);
-var result = stream.parallel().gather(limit(3L)).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B5.snippet b/java24/Gatherers_B5.snippet
deleted file mode 100644
index 0559313..0000000
--- a/java24/Gatherers_B5.snippet
+++ /dev/null
@@ -1,16 +0,0 @@
-// Distinct Gatherer
-static Gatherer distinct() {
- return Gatherer.ofSequential(
- () -> new HashSet(),
- (set, element, downstream) -> {
- if (set.add(element)) {
- return downstream.push(element);
- }
- return true;
- }
- );
-}
-
-var stream = Stream.of(1, 1, 2, 2, 2, 3, 4, 4, 4, 5);
-var result = stream.gather(distinct()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B6.snippet b/java24/Gatherers_B6.snippet
deleted file mode 100644
index be2adc5..0000000
--- a/java24/Gatherers_B6.snippet
+++ /dev/null
@@ -1,23 +0,0 @@
-// Distinct Parallel Gatherer
-static Gatherer distinct() {
- return Gatherer.of(
- () -> new HashSet(),
- (set, element, _) -> {
- set.add(element);
- return true;
- },
- (set1, set2) -> {
- set1.addAll(set2);
- return set1;
- },
- (set, downstream) -> {
- set.stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-var stream = Stream.of(1, 1, 2, 2, 2, 3, 4, 4, 4, 5);
-var result = stream.parallel().gather(distinct()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B7.snippet b/java24/Gatherers_B7.snippet
deleted file mode 100644
index d8b68c1..0000000
--- a/java24/Gatherers_B7.snippet
+++ /dev/null
@@ -1,24 +0,0 @@
-// Sort Gatherer
-static Gatherer sortWithComparator(Comparator super T> comparator) {
- return Gatherer.ofSequential(
- () -> new ArrayList(),
- (list, element, _) -> {
- list.add(element);
- return true;
- },
- (list, downstream) -> {
- list.sort(comparator);
- list.stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-static > Gatherer sort() {
- return sortWithComparator(Comparator.naturalOrder());
-}
-
-var stream = Stream.of(3, 2, 4, 5, 3, 1, 2, 5, 4);
-var result = stream.gather(sort()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B8.snippet b/java24/Gatherers_B8.snippet
deleted file mode 100644
index 51e101b..0000000
--- a/java24/Gatherers_B8.snippet
+++ /dev/null
@@ -1,48 +0,0 @@
-// Sort Parallel Gatherer
-static Gatherer sortWithComparator(Comparator super T> comparator) {
-
- return Gatherer.of(
- () -> new ArrayList(),
- (list, element, _) -> {
- list.add(element);
- return true;
- },
- (list1, list2) -> {
- list1.sort(comparator);
- list2.sort(comparator);
- int initialCapacity = list1.size() + list2.size();
- var list3 = new ArrayList(initialCapacity);
- for (int index1 = 0, index2 = 0, index3 = 0; index3 < initialCapacity; index3++) {
- if (index1 < list1.size() && index2 < list2.size()) {
- if (comparator.compare(list1.get(index1), list2.get(index2)) < 0) {
- list3.add(list1.get(index1));
- index1++;
- } else {
- list3.add(list2.get(index2));
- index2++;
- }
- } else if (index1 < list1.size()) {
- list3.add(list1.get(index1));
- index1++;
- } else if (index2 < list2.size()) {
- list3.add(list2.get(index2));
- index2++;
- }
- }
- return list3;
- },
- (list, downstream) -> {
- list.stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-static > Gatherer sort() {
- return sortWithComparator(Comparator.naturalOrder());
-}
-
-var stream = Stream.of(3, 2, 4, 5, 3, 1, 2, 5, 4);
-var result = stream.parallel().gather(sort()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_B9.snippet b/java24/Gatherers_B9.snippet
deleted file mode 100644
index 96f3e55..0000000
--- a/java24/Gatherers_B9.snippet
+++ /dev/null
@@ -1,25 +0,0 @@
-// Sort Distinct Gatherer
-static Gatherer sortDistinctWithComparator(Comparator super T> comparator) {
-
- return Gatherer.ofSequential(
- () -> new TreeSet(comparator),
- (list, element, _) -> {
- list.add(element);
- return true;
- },
- (list, downstream) -> {
- list.stream()
- .takeWhile(_ -> !downstream.isRejecting())
- .forEach(downstream::push);
- }
- );
-}
-
-static > Gatherer sortDistinct() {
- return sortDistinctWithComparator(Comparator.naturalOrder());
-}
-
-
-var stream = Stream.of(3, 2, 4, 5, 3, 1, 2, 5, 4);
-var result = stream.gather(sortDistinct()).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_D1.snippet b/java24/Gatherers_D1.snippet
deleted file mode 100644
index d1fc6b9..0000000
--- a/java24/Gatherers_D1.snippet
+++ /dev/null
@@ -1,65 +0,0 @@
-// Zipping Gatherer
-static Gatherer zip(
- Iterable iterable) {
-
- class State {
- private final Iterator iterator;
- private boolean nextIsElement = true;
- private boolean hasNextElement = false;
- private T element;
-
- State(Iterator iterator) {
- this.iterator = iterator;
- }
-
- boolean hasNext() {
- if (nextIsElement) {
- return hasNextElement;
- } else {
- return iterator.hasNext();
- }
- }
-
- T next() {
- if (nextIsElement) {
- nextIsElement = false;
- hasNextElement = false;
- return element;
- } else {
- nextIsElement = true;
- return iterator.next();
- }
- }
-
- public void addElement(T element) {
- this.element = element;
- this.hasNextElement = true;
- }
- }
-
- return Gatherer.ofSequential(
- () -> new State(iterable.iterator()),
- (state, element, downstream) -> {
- state.addElement(element);
- if (state.hasNext()) {
- boolean isRejecting = !downstream.push(state.next());
- if (isRejecting) {
- return false;
- }
- }
- if (state.hasNext()) {
- boolean isRejecting = !downstream.push(state.next());
- if (isRejecting) {
- return false;
- }
- }
- return true;
- }
- );
-}
-
-var evens = List.of(0, 2, 4, 6, 8);
-var odds = List.of(1, 3, 5);
-
-var result = evens.stream().gather(zip(odds::iterator)).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_D2.snippet b/java24/Gatherers_D2.snippet
deleted file mode 100644
index 5efcddd..0000000
--- a/java24/Gatherers_D2.snippet
+++ /dev/null
@@ -1,71 +0,0 @@
-// Zipping With Default Value Gatherer
-static Gatherer zip(
- Iterable iterable,
- T defaultValue) {
-
- class State {
- private final Iterator iterator;
- private boolean nextIsElement = true;
- private boolean hasNextElement = false;
- private T element;
-
- State(Iterator iterator) {
- this.iterator = iterator;
- }
-
- boolean hasNext() {
- if (nextIsElement) {
- return hasNextElement;
- } else {
- return true;
- }
- }
-
- T next() {
- if (nextIsElement) {
- nextIsElement = false;
- hasNextElement = false;
- return element;
- } else {
- nextIsElement = true;
- if (iterator.hasNext()) {
- return iterator.next();
- } else {
- hasNextElement = false;
- return defaultValue;
- }
- }
- }
-
- public void addElement(T element) {
- this.element = element;
- this.hasNextElement = true;
- }
- }
-
- return Gatherer.ofSequential(
- () -> new State(iterable.iterator()),
- (state, element, downstream) -> {
- state.addElement(element);
- if (state.hasNext()) {
- boolean isRejecting = !downstream.push(state.next());
- if (isRejecting) {
- return false;
- }
- }
- if (state.hasNext()) {
- boolean isRejecting = !downstream.push(state.next());
- if (isRejecting) {
- return false;
- }
- }
- return true;
- }
- );
-}
-
-var evens = List.of("0", "2", "4", "6", "8");
-var odds = List.of("1", "3", "5");
-
-var result = evens.stream().gather(zip(odds::iterator, "NO_VALUE")).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_D3.snippet b/java24/Gatherers_D3.snippet
deleted file mode 100644
index 24ffe6f..0000000
--- a/java24/Gatherers_D3.snippet
+++ /dev/null
@@ -1,22 +0,0 @@
-// Combining Gatherer
-static Gatherer zip(
- Iterable iterable,
- BiFunction super T, ? super R, ? extends RR> combiner) {
-
- return Gatherer.ofSequential(
- iterable::iterator,
- (iterator, element, downstream) -> {
- if (iterator.hasNext()) {
- var result = combiner.apply(element, iterator.next());
- return downstream.push(result);
- }
- return false;
- }
- );
-}
-
-var strings = List.of("one", "two", "three");
-var ints = List.of(1, 2, 3, 4, 5);
-
-var result = ints.stream().gather(zip(strings, (i, s) -> i + " -> " + s)).toList();
-System.out.println("result = " + result);
diff --git a/java24/Gatherers_D4.snippet b/java24/Gatherers_D4.snippet
deleted file mode 100644
index c58e499..0000000
--- a/java24/Gatherers_D4.snippet
+++ /dev/null
@@ -1,25 +0,0 @@
-// Combining With Default Value Gatherer
-static Gatherer zip(
- Iterable iterable,
- BiFunction super T, ? super R, ? extends RR> combiner,
- R defaultValue) {
-
- return Gatherer.ofSequential(
- iterable::iterator,
- (iterator, element, downstream) -> {
- if (iterator.hasNext()) {
- var result = combiner.apply(element, iterator.next());
- return downstream.push(result);
- } else {
- var result = combiner.apply(element, defaultValue);
- return downstream.push(result);
- }
- }
- );
-}
-
-var strings = List.of("one", "two", "three");
-var ints = List.of(1, 2, 3, 4, 5);
-
-var result = ints.stream().gather(zip(strings, (i, s) -> i + " -> " + s, "NO_VALUE")).toList();
-System.out.println("result = " + result);
diff --git a/java24/StatementsBeforeSuper_1.snippet b/java24/StatementsBeforeSuper_1.snippet
deleted file mode 100644
index 21dcf15..0000000
--- a/java24/StatementsBeforeSuper_1.snippet
+++ /dev/null
@@ -1,34 +0,0 @@
-// Statement before super
-static class Shape {
- private String name;
- public Shape(String name) {
- if (name == null) {
- throw new IllegalArgumentException("User should not be null");
- }
- super();
- this.name = name;
- }
- public String name() {
- return name;
- }
-}
-
-static class Square extends Shape {
- private int edge;
- public Square(int edge) {
- if (edge <= 0) {
- throw new IllegalArgumentException("Edge should be greater than 0");
- }
- super("Square");
- this.edge = edge;
- }
- public int edge() {
- return edge;
- }
- public String toString() {
- return "Square[" + edge + "]";
- }
-}
-
-Square square = new Square(100);
-System.out.println("square = " + square);
diff --git a/snippets/hello-world.snippet b/snippets/hello-world.snippet
new file mode 100644
index 0000000..d83ace4
--- /dev/null
+++ b/snippets/hello-world.snippet
@@ -0,0 +1,3 @@
+var name = "Duke";
+
+System.out.println("Hello, " + name);
diff --git a/snippets/index.json b/snippets/index.json
new file mode 100644
index 0000000..dd4439a
--- /dev/null
+++ b/snippets/index.json
@@ -0,0 +1,20 @@
+{
+ "misc/simple-collection.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/misc/simple-collection.snippet",
+ "misc/func-interface.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/misc/func-interface.snippet",
+ "misc/functions-chaining.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/misc/functions-chaining.snippet",
+ "records/composing.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/records/composing.snippet",
+ "records/simple.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/records/simple.snippet",
+ "records/method-overriding.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/records/method-overriding.snippet",
+ "streams/filtering.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/streams/filtering.snippet",
+ "streams/stream-to-list.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/streams/stream-to-list.snippet",
+ "streams/text-block-to-stream.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/streams/text-block-to-stream.snippet",
+ "textblocks/formatting.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/textblocks/formatting.snippet",
+ "textblocks/simple.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/textblocks/simple.snippet",
+ "textblocks/record.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/textblocks/record.snippet",
+ "hello-world.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/hello-world.snippet",
+ "switch/expression.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/switch/expression.snippet",
+ "switch/pattern-matching.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/switch/pattern-matching.snippet",
+ "switch/statement.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/switch/statement.snippet",
+ "pattern-matching/record.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/pattern-matching/record.snippet",
+ "pattern-matching/switch.snippet": "https://raw.githubusercontent.com/java/playground-snippets/main/pattern-matching/switch.snippet"
+}
\ No newline at end of file
diff --git a/java21/Misc1.snippet b/snippets/misc/func-interface.snippet
similarity index 89%
rename from java21/Misc1.snippet
rename to snippets/misc/func-interface.snippet
index 6a6d5d3..1f8db85 100644
--- a/java21/Misc1.snippet
+++ b/snippets/misc/func-interface.snippet
@@ -1,4 +1,3 @@
-// Functional Interface
@FunctionalInterface
interface MyFunctionalInterface {
public int incrementByTwo(int a);
diff --git a/java21/Misc3.snippet b/snippets/misc/functions-chaining.snippet
similarity index 94%
rename from java21/Misc3.snippet
rename to snippets/misc/functions-chaining.snippet
index 5be33d7..cb53b20 100644
--- a/java21/Misc3.snippet
+++ b/snippets/misc/functions-chaining.snippet
@@ -1,4 +1,3 @@
-// Functions chaining
var strings = Arrays.asList("one", null, "three", "", "five", "six");
Function handleNull = s -> s == null ? "": s;
diff --git a/java21/Misc2.snippet b/snippets/misc/simple-collection.snippet
similarity index 88%
rename from java21/Misc2.snippet
rename to snippets/misc/simple-collection.snippet
index 715a600..d3f735f 100644
--- a/java21/Misc2.snippet
+++ b/snippets/misc/simple-collection.snippet
@@ -1,4 +1,3 @@
-// Simple collection
Collection numbers = new ArrayList<>();
numbers.add("one");
numbers.add("two");
diff --git a/java21/PatternMathcing.snippet b/snippets/pattern-matching/record.snippet
similarity index 96%
rename from java21/PatternMathcing.snippet
rename to snippets/pattern-matching/record.snippet
index e03f2b4..cec18ca 100644
--- a/java21/PatternMathcing.snippet
+++ b/snippets/pattern-matching/record.snippet
@@ -1,4 +1,3 @@
-// For instanceof
record Point(int x, int y) {
public boolean equals(Object other) {
return other instanceof Point otherPoint &&
diff --git a/snippets/pattern-matching/switch.snippet b/snippets/pattern-matching/switch.snippet
new file mode 100644
index 0000000..b6f622b
--- /dev/null
+++ b/snippets/pattern-matching/switch.snippet
@@ -0,0 +1,23 @@
+record Point(int x, int y) {}
+
+record Circle(Point center, int radius) {
+ public Circle {
+ if (radius < 0) throw new IllegalArgumentException("Radius cant be null");
+ }
+}
+
+ToDoubleFunction