Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Comments on Tips for golfing in Java

Parent

Tips for golfing in Java

+2
−0

This is a list of golfing tips for the language known as Java. If you have a tip, add it in!

History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

Don't use Java. (3 comments)
Post
+3
−0

Use higher versions of Java

Seriously, it's crazy what sort of features have been added since Java 8. I hardly recognize the language anymore...

Examples:

Constructing Lists

Before, you had to do something like Arrays.asList(new String[]{"a", "b", "c"}), but in Java 9+ you have List.of("a", "b", "c"), some huge savings.

var keyword

Self explanatory - since Java 10, instead of ReallyLongTypeName a = x();, you now can just do var a = x();.

Strings

In Java 11, some cool stuff for Strings was added that could potentially be useful - for example, .lines() returns the String separated by newlines as a Stream (saving over .split("\n")).

Fancy switch statements

Before:

switch(thing){case A:return "a";case B:return "b";default:return "x";}

Java 13+:

return switch(thing){case A->"a";case B->"b";default->"x";}

You can even have blocks of statements in any of the cases using {}.

There are many other new features that I did not think are relavant to golf, and many many others that I'm sure I missed - there is just so much stuff to unpack. Please contribute if you find something I missed!

History
Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment thread

Great tip! It's not just Strings, Java 9, 11, etc. added some methods to `Stream`s too (e.g. `takeWhi... (1 comment)
Great tip! It's not just Strings, Java 9, 11, etc. added some methods to `Stream`s too (e.g. `takeWhi...
user‭ wrote over 2 years ago · edited over 2 years ago

Great tip! It's not just Strings, Java 9, 11, etc. added some methods to Streams too (e.g. takeWhile). The newer versions actually makes programming in Java enjoyable. There's also Map.of, although that's less often needed.