DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • Build a Voice Assistant With Gemini Live API
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • How an AI Software Factory Works: From Developer Intent to Production
  • Avoiding AI Debt as a Team

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Writing One-liners in Java 8

Writing One-liners in Java 8

Learn how to write "one-liners" in Java 8, and no, we're not talking bad jokes here.

By 
Ganesh Samarthyam
·
Mar. 31, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
17.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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:

—

Files.lines(Paths.get(“./FileRead.java”)).forEach(System.out::println);

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>.

new Random().ints().limit(5).forEach(System.out::println);

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

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook