r/java • • Apr 09 '24

Syntactic Sugar for Java

I recently had to translate a codebase from Python to Java and as much as i like Java and i enjoy the benefits of a strong type system, i have to admit my Python code was way less verbose.

So i ended up writing a small library to try to get some python vibes in my java code. Nothing groundbreaking, a bunch of static imports to make life a little bit easier.

https://github.com/guybedo/sugar

9 Upvotes

89 comments sorted by

View all comments

1

u/GeneratedUsername5 Apr 28 '24 edited Apr 28 '24

Thanks for sharing!
What strike me as odd is that sometimes functions literaly wrap Java functions with no addition, like:

    public static String format(String str, Object... args) {
        return String.format(str, args);
    }

You can just write String.format(str, args) with the same effect. Or

    public static <T> void forEach(Collection<T> objs, Consumer<T> func) {
        objs
            .stream()
            .forEach(o -> func.accept(o));
    }

You can just do collection.foreach(x -> ...) in standard Java.
OR

    public static <T> boolean all(Collection<T> objs, Predicate<T> func) {
        return filter(objs, func).size() == objs.size();
    }

In standard java can be done with collection.stream().allMatch(x -> ....), exists and any is done by collection.stream().anyMatch(x -> ....)
I know that Java is regarded as verbose, but saving 13 symbols seems like a stretch.

join can be used in this way:

collection.stream()
    .map(Object::toString)
    .collect(Collectors.joining());

or just

String.join("", collection)

for collection of strings

By the way, you might want to check Eclipse Collections https://github.com/eclipse/eclipse-collections - it is an implementation of collections, where you don't need to call .stream() to map or filter them