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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Monolith: The Good, The Bad and The Ugly
  • Scaling Microservices With Docker and Kubernetes on Production
  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 user avatar
Ganesh Samarthyam
·
Mar. 31, 16 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
16.6K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!