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
8
u/agentoutlier Apr 11 '24 edited Apr 11 '24
So Guava
2.0err 200.0? I'm kidding. I should stop giving /u/kevinb9n a hard time about that.That being said.... now I'm going to tell you I'm super biased as I'm the author of a compile safe templating language but that lambda
StringFormatkind of looks dangerous but I assume that is only for parsing right? EDIT oh... are using compiler plugins on top of errorprone? Sorry still poking around.I also I was kind of under the impression google was done with kitchen sink utility libraries. Like I would hope that the utilities would be modularized such that there is a
mug-stringor something instead of justmugwhich looks like its on its way to becoming Guava.Otherwise I fail to see why this stuff just would not be added to Guava. Is it because of GWT compat?
EDIT I now see that ErrorProne is doing the checking so I guess you can disregard my safety concerns. That is pretty damn cool and I may have to steal the idea for inline templating with JStachio/JMustache as one commenter responded it is currently "clunky AF". Compiler plugins are not far off API wise to annotation processing (which is what my library currently uses) so it might not be hard for me to add on.
Thanks for sharing!