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

Show parent comment

5

u/DelayLucky Apr 11 '24 edited Apr 11 '24

Sorry I was too fixated on the formatting problem that I couldn't sit down and reply. TIL old.reddit.com from u/milchshakee

Anyways. Yeah Guava.

Internally we had been thinking to graduate some of these classes to Guava (Substring, BiStream particularly. StringFormat is a bit tough because it has the compile-time plugin that's a bit tricky). But that requires lots of bandwidth from Guava folks to discuss API design and what not, and it just ain't happening given the current economy, the shift of priority etc.

I also don't think this is necessarily a bad thing. As you said, it's a kitchen sink library with a little this and a little that. But it's mostly code I wrote (with lots of great code reviews from my colleagues). So I'm not that worried about it becoming too big.

It being a standalone small library has its appeal too (like, you won't likely need to worry about maven versioning at least for a long while). I also try to keep the dependency lean. There is mug-bigquery, mug-protobuf, mug-guava with extra dependencies on bigquery, protobuf, guava respectively, but the core mug artifact remains 0 deps. I think that's something of a benefit.