Last active
March 1, 2021 14:08
-
-
Save kamchy/ec66d9fcc5021f2f4b3813285c3c7190 to your computer and use it in GitHub Desktop.
Java 14: Example of records and text blocks
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
package com.kamilachyla.bggen; | |
import java.awt.*; | |
import java.util.Arrays; | |
import java.util.function.BiFunction; | |
import java.util.function.UnaryOperator; | |
import java.util.stream.Stream; | |
public class Main { | |
record HSL(float hue, float saturation, float lightness){ | |
public static HSL of(float h, float s, float l) { | |
return new HSL(h, s, l); | |
} | |
public Color toColor() { | |
return Color.getHSBColor(hue, saturation, lightness); | |
} | |
} | |
static String toHexString(Color c) { | |
return String.format("#%s%s%s%s", | |
Integer.toHexString(c.getRed()), | |
Integer.toHexString(c.getGreen()), | |
Integer.toHexString(c.getBlue()), | |
Integer.toHexString(c.getAlpha())); | |
} | |
private static UnaryOperator<HSL> nextHSLBy(float delta) { | |
return (t) -> HSL.of(t.hue + delta, t.saturation, t.lightness); | |
} | |
private static String colorInfo(String name, Color c) { | |
return String.format(""" | |
%s: %s (%s) | |
""", name, c, toHexString(c)); | |
} | |
private static String colorJson(String name, Color c) { | |
return String.format(""" | |
{"%s": {"r": %s, "g":%s, "b":%s, "hex":%s}} | |
""", name, c.getRed(), c.getGreen(), c.getBlue(), toHexString(c)); | |
} | |
private static void showInfo() { | |
System.out.printf(""" | |
HSL: Is record? %s | |
HSL: components: | |
""", HSL.class.isRecord()); | |
Arrays.stream(HSL.class.getRecordComponents()).forEach(rc -> | |
System.out.printf(""" | |
Component name: %s, | |
Component type: %s | |
""", rc.getName(), rc.getType())); | |
} | |
private static void generateColors(BiFunction<String, Color, String> colorFormatter) { | |
var count = 20; | |
HSL initialColor = HSL.of(0.3f, 0.4f, 0.8f); | |
Stream<HSL> colStream = Stream.iterate(initialColor, Main.nextHSLBy(0.04f)); | |
colStream.limit(count).map(HSL::toColor).map(c -> colorFormatter.apply("color", c)).forEach(System.out::println); | |
} | |
public static void main(String[] args) { | |
generateColors(Main::colorJson); | |
showInfo(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment