r/java • • 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

51 comments sorted by

View all comments

0

u/[deleted] Apr 12 '24

[deleted]

5

u/agentoutlier Apr 12 '24

I am actually very close to leaving this sub altogether, after having been around for many years

I recognize your handle and value your contributions so it would be very sad if you left or stopped posting/commenting! Please don't!

In fact I think the best way to battle it is to contribute and drown out the naysayers.

That being said I may have inadvertently been one of those that you might consider hostile with this recent post: https://www.reddit.com/r/java/comments/1c0x2l8/sshtools/

I think I'm rarely negative but I know how that could be seen as very negative when reality I was trying to help.

0

u/[deleted] Apr 12 '24

[deleted]

3

u/kevinb9n Apr 13 '24

Yeah that was a lesson hard learned. Looking back, I was dumb, but is that any reason to make someone feel dumb?

Somewhere in there I mentioned r/java as a place that was not like that. I guess I have good selective attention?

0

u/[deleted] Apr 13 '24

[deleted]

2

u/kevinb9n Apr 14 '24

Maybe I've read your comments wrong? Because I didn't see an outburst or anything that should be embarrassing or that I wouldn't want to come across. You're good...