Comments on Tips for golfing in Java
Parent
Tips for golfing in Java
This is a list of golfing tips for the language known as Java. If you have a tip, add it in!
Use higher versions of Java …
3y ago
Use `interface` The special …
3y ago
Abuse anonymous classes War …
3y ago
Abuse the C-like array syntax …
3y ago
Use `for(;;)` instead of `whil …
3y ago
A clever way to replace `Math` …
3y ago
Booleans are replaceable Ja …
3y ago
Post
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!
1 comment thread