Small Java 25 utility library built on top of fastutil.
Note
The library doesn't check @NotNull values for null - expect the result of such actions to be undefined.
Helpers for working with numbers. Parsing returns a fallback instead of throwing on a malformed string.
NumberUtils.parseInt("42", 0); // 42
NumberUtils.parseInt("many", 0); // 0, the fallback
NumberUtils.parseDouble(null, 1.5); // 1.5There are parseInt, parseLong and parseDouble. Without a fallback they return an OptionalInt, OptionalLong or OptionalDouble.
parseNumber returns the narrowest of Integer, Long and Double that holds a plain decimal number, like 12, 9999999999 or 6.5.
A range of numbers.
Range.Interval dice = Range.of(Bound.inclusive(1), Bound.exclusive(7)); // [1, 7), Bound.infinite() leaves a side unbounded
dice.contains(7); // false
dice.max().inclusive(); // false, the upper bound is Bound.OfLong 7; effectiveInt(true) gives 6, the largest int below it
RngUtils.inRange(dice, 0); // 1..6, the fallback is for a range without such values
Range.Interval ratio = Range.Interval.parse("(0, 2.5]"); // an empty bound like in [1, ) is unbounded
Range.parse("[1, x]"); // Range.EMPTY, like any range without numbers between its bounds, such as [7, 1]; see isEmpty()
Range gaps = dice.or(Range.parse("[10, 12]")); // [1, 7) U [10, 12], a Range.Compound with its intervals(), parsed back by Range.parse
gaps.and(Range.parse("[5, 11)")); // [5, 7) U [10, 11)
RngUtils.inRange(gaps, 0); // each of 1..6 and 10..12 is equally likelyHashList is an unmodifiable List with O(1) contains, indexOf and lastIndexOf, for when a list needs both order and fast lookups.
A custom fastutil Hash.Strategy can be used to change how elements are compared.
HashList<String> ci = HashList.ofCustom(CaseInsensitive.strategy(), "Alpha", "Beta");
ci.contains("ALPHA"); // trueCaseInsensitive provides fastutil maps and sets with case-insensitive String keys that keep the original casing.
RngUtils has shortcuts for picking random elements of arrays and collections, and random values in ranges.
All methods use ThreadLocalRandom by default or accept any RandomGenerator.
String color = RngUtils.randomElement(List.of("red", "green", "blue"));
int roll = RngUtils.inRange(1, 7); // 1..6
Duration delay = RngUtils.inRange(Duration.ofSeconds(1), Duration.ofSeconds(5));
List<String> winners = RngUtils.randomElements(players, 3, new ArrayList<>()); // up to 3 distinct, in their original order
RngUtils.forRandomElements(players, 3, System.out::println);WeightedPicker picks elements with probability proportional to their weight. It is immutable, so one picker can be reused.
WeightedPicker<String> loot = new WeightedPicker.Composer<String>()
.add("common", 9)
.add("rare", 1)
.finish();
String drop = loot.next(RngUtils.threadRandom()); // "common" 90% of the timePickers can also be created from a map of weights, or from a collection with a function that computes each element's weight. Elements with zero or negative weight are never picked. If any element has an infinite weight, only such elements are picked.
Chance is a reusable probability that can be tested against any RandomGenerator, or ThreadLocalRandom by default.
Chance crit = Chance.of(0.2);
boolean critical = crit.test(); // true 20% of the time
Chance.of(1); // Chance.Constant.ALWAYS; 0 or less gives NEVER, 0.5 gives COIN_FLIPParses human-written durations like 1h 30m into java.time.Duration, and formats them back.
DurationUtils.parseDuration("1h 30m"); // Optional of 90 minutes, empty if malformed
DurationUtils.parseDuration("90"); // no unit means seconds by default
DurationUtils.parseDuration("1h -15m"); // each part can be negative, 45 minutes
DurationUtils.parseDuration("2min", Map.of("min", ChronoUnit.MINUTES)); // custom units
DurationUtils.parseDurationStrict("1h 30m"); // the Duration itself, throws IllegalArgumentException if malformedDefault units: ns, ms, s, m, h, d, case-insensitive.
DurationUtils.serializeDuration(Duration.ofMinutes(90)); // "1h 30m"
DurationUtils.serializeDuration(Duration.ofMillis(-1500)); // "-1s -500ms"It also checks whether enough time has passed between two points in time.
boolean ready = DurationUtils.hasElapsed(lastUse, Instant.now(), Duration.ofSeconds(5)); // true once 5 seconds have passedShared constant predicates and lenient boolean parsing.
Predicate<Player> filter = BooleanUtils.alwaysTrue(); // or always(boolean) to pick one
BooleanUtils.parseBoolean("TRUE"); // Boolean.TRUE, null unless true/falseA boolean with a third UNSET state, for things like "not configured" or "doesn't matter".
Mirrors the Optional API: presence checks, fallbacks, ifPresent, orElseThrow.
TriState flag = TriState.parseNatural("yes"); // TRUE
TriState.parse("yes"); // UNSET, only true/false are recognized
flag.asBoolean(false); // true
TriState.UNSET.asBoolean(false); // false, the fallback
// UNSET works as a wildcard filter
TriState requireOp = TriState.UNSET;
requireOp.isValidFor(player.isOp()); // true for any playerTriState.parseNatural(String) uses TriState.Mapper.NATURAL, which understands true/on/yes/allow/enable and their negatives. Anything else is UNSET.
TriState.Mapper converts between states and strings with custom words.
Each state has a main name, used when converting back to a string. TRUE and FALSE can also have extra variants that are accepted when parsing.
Matching ignores case, and unknown strings or null give the fallback state (UNSET unless changed with fallback(...)).
TriState.Mapper mapper = TriState.Mapper.builder()
.name(TriState.TRUE, "allow")
.name(TriState.FALSE, "deny")
.name(TriState.UNSET, "default")
.addVariants(true, "yes", "+")
.addVariants(false, "no", "-")
.build();
mapper.parse("YES"); // TRUE
mapper.parse("maybe"); // UNSET, the fallback
mapper.name(TriState.FALSE); // "deny"
mapper.strings(TriState.TRUE); // [allow, yes, +]An existing mapper can be extended with toBuilder(), e.g. to add words to Mapper.NATURAL.
build() throws if the same word is assigned to different states.
The result of a comparison as a constant: BELOW, EQUAL or ABOVE, instead of the sign of an int.
Comparison.of(5, 10); // BELOW, by natural order
Comparison.of("b", "a"); // ABOVE
Comparison.of(String.CASE_INSENSITIVE_ORDER, "A", "a"); // EQUAL, with a comparator
Comparison.is(7, Comparison.EQUAL, 7); // true, reads as "7 is EQUAL 7"
Comparison.ofSignum(-42); // BELOW, for the result of compareTo or compareHelpers for working with enums. Looking up a constant by name ignores case and returns a fallback when there is no match.
EnumUtils.parseEnum("fast", Mode.SLOW); // Mode.FAST
EnumUtils.parseEnum("warp", Mode.SLOW); // Mode.SLOW, the fallback
EnumUtils.parseEnum("warp", Mode.class); // Optional.empty(), there is no fallbackHelpers to act on a value inline, without temporary variables.
Map<String, Integer> ids = FluentUtils.peek(new HashMap<>(), map -> map.put("admin", 0));
int length = FluentUtils.map(parameter.get("name").textValue(), String::length);
String name = FluentUtils.orElse(System.getenv("USER_NAME"), "guest");
Config config = FluentUtils.orElseGet(cachedConfig, Config::load); // load() is only called if cachedConfig is null
Optional<UUID> id = FluentUtils.attempt(() -> UUID.fromString(input)); // empty if parsing throws
UUID owner = FluentUtils.attemptOrElse(() -> UUID.fromString(input), new UUID(0, 0)); // the fallback if parsing throwsCompares objects by the values they hold. This is looser than equals: values written or typed differently can still match.
Parameter.parseMap("a:1 b:'x'").matches(Parameter.parseMap("b:x a:1")); // true, quoting, spacing and entry order are ignored
Range.parse("[1, 2]").matches(Range.parse("[1.0, 2.0]")); // true, but equals(...) is false
Range.parse("[1, 2]").matches(Range.parse("[1, 2)")); // false, the upper bounds differIndex-aware search and replace, plus char array counterparts of common String methods.
TextUtils.replaceEach("a-b-c", "-", index -> "[" + index + "]"); // "a[1]b[3]c"
TextUtils.findEach("1a 2a 3a", "a", index -> System.out.println(index)); // 1, 4, 7
char[] chars = "key:value".toCharArray();
int colonAt = TextUtils.indexOf(chars, ':'); // 3
TextUtils.substring(chars, 0, colonAt); // "key"
TextUtils.subarray(chars, colonAt + 1); // ['v', 'a', 'l', 'u', 'e']An empty search string matches nothing.
Parses compact, human-written parameter strings (commands, config values, tags) into a tree of values, lists and maps.
- Values are separated by whitespace.
key:valuemakes a map entry,[...]a list,{...}a nested map. <?>is a missing value.<! any text>is a comment, skipped entirely.- Values containing whitespace, colons or brackets are quoted with
'...';\and'are escaped with\. - The top level can be parsed as either a map or a list, without the wrapping brackets.
Parameter config = Parameter.parseMap(
"title:'Main servers' servers:[{host:eu.example.com ports:[25565 25566]} {host:us.example.com}]"
);
config.get("title").textValue(); // "Main servers"
config.get("servers").count(); // 2
config.get("servers").get(0).get("ports").get(1).textValue(); // "25566"
config.get("servers").get(7).get("host").isMissing(); // true, there's no index 7
config.find("title"); // Optional of the title, empty if absent
config.get(Path.parse("servers.0.ports.1")).textValue(); // "25566", find(...) and getText(...) take a Path too
Path.parse("a\\.b.c"); // steps "a.b" and "c", the backslash escapes the dot; Path.parse("a/b", '/') splits by another char. A number is a list index
config.forKeyed((key, value) -> System.out.println(key)); // title, servers
config.get("servers").forIndexed((index, server) -> System.out.println(index + " " + server.getText("host"))); // 0 eu.example.com, 1 us.example.com
config.keys(); // ["title", "servers"], a list would have its indexesLookups never return null or throw: anything absent is Parameter.missing(), which can be chained further. Map keys are case-insensitive.
There is a single Parameter type: isList(), isMap() and isPlain() tell the kinds apart, isMissing() an absent one.
Unquoted values that look like an int, long, double or true/false are parsed into their type, and keep the exact text they were written with.
Values are read with a fallback for absent and malformed ones:
Parameter config = Parameter.parseMap("name:Main port:25565 ratio:0.5 debug:true mode:fast");
config.getText("name"); // "Main"
config.get("port").asInt(); // OptionalInt[25565], empty if absent or malformed
config.get("timeout").asInt(30); // 30, it's absent
config.get("ratio").asDouble(1.0); // 0.5
config.get("debug").asBoolean(); // true, only true/false are recognized
config.get("verbose").asTriState(); // TriState.UNSET, it's absent; accepts words like yes/on
config.get("mode").asEnum(Mode.SLOW); // Mode.FAST, ignoring case
config.get("id").as(UUID::fromString); // own parsing for any typeParameters can be built in code with ofValue(...), ofList(...) and ofMap(...) (null and missing entries are skipped, map entries keep their iteration order).
ofValue(...) also takes an int, long, double, boolean, TriState or enum constant, which the matching asX() returns without parsing.
Parameter server = Parameter.ofMap(Map.of(
"host", Parameter.ofValue("eu.example.com"),
"ports", Parameter.ofList(List.of(Parameter.ofValue(25565), Parameter.ofValue(25566)))
));serialize(...) turns a parameter back into a normalized string that parses to the same thing, and matches(...) compares two ignoring quoting, spacing and map entry order.
Parameters are immutable. with(...) returns a modified copy, setting a key on a map or an index on a list. For several edits, editList() and editMap() apply them with a single copy:
Parameter list = Parameter.parseList("a b c");
list.with(1, Parameter.ofValue("B")); // [a B c]
list.with(4, Parameter.ofValue("e")); // [a b c <?> e], the gap is filled with missing
list.editList().insert(1, Parameter.ofValue("x")).remove(0).finish(); // [x b c]parseMapStrict and parseListStrict throw IllegalArgumentException on malformed input: an unterminated list, map or quote, a key without a colon, a stray closing bracket or a value nested too deep.
Nesting depth is limited to 512, configurable via the ink.glowing.utils.params.maxDepth system property.
Versions in dependency sections may be outdated. Check the badge above for the latest one.
fastutil is a provided dependency and must be available at runtime.
The library is split into two artifacts:
inkyutils-common- everything exceptparams.inkyutils-params-params, pulls ininkyutils-common.
Add to repositories
<repository>
<id>glowing-ink</id>
<url>https://repo.glowing.ink/releases</url>
<!-- https://repo.glowing.ink/snapshots for snapshots -->
</repository>Add to dependencies
<dependency>
<groupId>ink.glowing.utils</groupId>
<artifactId>inkyutils-common</artifactId>
<version>0.7.0</version>
</dependency>repositories {
maven {
url = uri("https://repo.glowing.ink/releases")
// https://repo.glowing.ink/snapshots for snapshots
}
}
dependencies {
implementation("ink.glowing.utils:inkyutils-common:0.7.0")
}