We all love one-liners, don’t we? The ones like these:
- “War does not determine who is right – only who is left.”
- “Always borrow money from a pessimist. He won’t expect it back.”
- “We live in a society where pizza gets to your house before the police.”
For techies like us, “one-liners” mean something different – it’s a program that is written in one line. Of course, C is my favourite for writing one-liners, like the following one that copies a string from source (variable “char *s”) to target (variable “char *t”):
while (*t++ = *s++);
That’s cute, isn’t it? Perl is another favourite language for writing one-liners (there is even a book on it!)
With lambda expressions and streams in Java 8, you can now write curt code in Java also. Here are some one-liners written in Java 8:
This code prints the contents of the file “FileRead.java” in the current directory. The java.nio.file.Filesclass has lines() method that returns a StreamString>.
Pattern.compile(” “).splitAsStream(“a be cee”).forEach(System.out::println);
This code splits the input string “a be cee” based on whitespace and hence prints the strings “a,” “be,” and “cee,” on the console. The java.util.Pattern class has splitAsStream() method that returns a StreamString>.
This code prints five random integers and prints them to the console. The java.util.Random class has ints() method that returns an IntStream. It generates an infinite stream of random integers; so to restrict the number of integers to 5 integers, we call limit(5) on that stream.
“hello”.chars().sorted().forEach(ch -> System.out.printf(“%c “, ch));
This code prints the characters e h l l o on the console.
The String class has chars() method (newly introduced in Java 8 in CharSequence—an interface that String class implements). This method returns an IntStream (why IntStream? Remember that there is no equivalent char specialization for Streams). This code calls sorted() method on this stream, so the stream elements get sorted in ascending order. Because it is a stream of integers, this code uses “%c” to explicitly force the conversion from int to char.
Few years back, if someone said you could write one-liners in Java (i.e., Java before version 7), I would have laughed: Java is so “verbose” that just getting Java to print “hello world” takes 8 lines or so! But with Java lambdas and streams (functional programming in Java), it is finally possible to write short but expressive code in Java.
If you are a Java programmer and haven’t done functional programming in Java 8, get started and explore the new way of programming in Java. A bonus is writing short code as illustrated by the one-liners in this article. Also, do check out this book for learning functional programming with lambdas and streams in Java 8. You can download source code here