Last active
September 21, 2023 12:55
-
-
Save edwingustafson/ee5e2f6ca238e9569a562fb5d804379b to your computer and use it in GitHub Desktop.
FizzBuzz demonstrating JDK 21 LTS features
This file contains hidden or 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 -S java --source 21 --enable-preview | |
| /* | |
| FizzBuzz demonstrating JDK 21 LTS features | |
| */ | |
| import java.util.Map; | |
| import java.util.Map.Entry; | |
| import java.util.stream.IntStream; | |
| class FizzBuzz { | |
| static final String FIZZ = "fizz"; | |
| static final String BUZZ = "buzz"; | |
| // String template | |
| static final String FIZZBUZZ = STR."\{FIZZ}\{BUZZ}"; | |
| static final int N = 3; | |
| static final int M = 5; | |
| static final int LIMIT = 64; | |
| static boolean divisibleBy(final int n, final int d) { | |
| return n % d == 0; | |
| } | |
| public static void main(final String args[]) { | |
| // Switch expression | |
| final Integer limit = switch(args) { | |
| case String[] a when a.length > 0 -> Integer.parseInt(a[0]); | |
| default -> LIMIT; | |
| }; | |
| IntStream.range(1, limit).forEach(n -> { | |
| final Map.Entry<Boolean, Boolean> pair = Map.entry( | |
| divisibleBy(n, N), | |
| divisibleBy(n, M) | |
| ); | |
| // Switch expression | |
| final String result = switch(pair) { | |
| case Map.Entry<Boolean, Boolean> e when e.getKey() && !e.getValue() -> FIZZ; | |
| case Map.Entry<Boolean, Boolean> e when !e.getKey() && e.getValue() -> BUZZ; | |
| case Map.Entry<Boolean, Boolean> e when e.getKey() && e.getValue() -> FIZZBUZZ; | |
| default -> String.valueOf(n); | |
| }; | |
| System.out.println(result); | |
| }); | |
| } | |
| } | |
| // vi:syntax=java |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment