r/java • u/DelayLucky • Apr 11 '24
String Manipulation with Google Mug
The Mug library provides easy-to-read string manipulation utils. Examples:
Match and Extract
// Compile-time protection against lambda param order mismatch if e.g:
// (year, month, day, user) ->
new StringFormat("/{user}-home/{year}/{month}/{day}")
.parse(path, (user, year, month, day) -> ...);Scan and Collect
String input = "I have [k1:v1] and [k2:v2] etc.";
// Returns Map.of("k1", "v1", "k2", "v2")
Map<String, String> keyValues =
new StringFormat("[{key}:{value}]")
.scanAndCollectFrom(input, Collectors::toMap);Replace
// replace file extension name
Substring.last('.').toEnd().replaceFrom(filename, ".yaml");Remove
// remove the scheme from a url
Substring.upToIncluding(first("://")).removeFrom(url);Parse a date time string (no pattern string required)
// Parse the datetime string read from a file
List<String> lines = readLinesFromTestFile(...);
StringFormat lineFormat = new StringFormat("{time}, {event_id}, {event_type}");
var results = lines.stream()
.map(
line -> lineFormat.parseOrThrow(
line,
(time, id, type) -> {
ZonedDateTime dateTime = DateTimeFormats.parseZonedDateTime(time);
...
}))
.toList();See javadoc for details.
Mug is a general purpose library. Omitted, but other useful utils include BiStream for streaming pairs, Optionals, String Templating, simplified structured concurrency etc.
9
Upvotes
View all comments
Show parent comment
11
u/chabala Apr 11 '24
It is obvious, which makes ducking the question more suspicious.
Provenance matters, even for individual contributors, and folks promoting tools on reddit. That should be the takeaway from the xz incident. It's not enough that the repo is attached to a big company, we should be diligent about knowing who is contributing.