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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Thread-Safety Pitfalls in XML Processing
  • Java Stream API: 3 Things Every Developer Should Know About
  • Understanding Lazy Evaluation in Java Streams
  • Exploring TakeWhile and DropWhile Functions in Java

Trending

  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Rethinking Recruitment: A Journey Through Hiring Practices
  • From Zero to Production: Best Practices for Scaling LLMs in the Enterprise
  1. DZone
  2. Coding
  3. Java
  4. SQL-Like Operations With Java Using Streams

SQL-Like Operations With Java Using Streams

Among the Streams API's uses is easily processing data. Here is how to get SQL-like functionality out of your Streams with some best practices to keep in mind.

By 
Harinath Kuntamukkala user avatar
Harinath Kuntamukkala
·
Jul. 12, 17 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
18.2K Views

Join the DZone community and get the full member experience.

Join For Free

Nearly every Java application makes and processes collections to group and process the data. To process the data from collections, we write a lot of boilerplate code. Typical processing patterns on collections are similar to SQL-like operations such as “finding”, “grouping”, etc. Most databases let us specify such operations declaratively like the below SQL query:

SELECT dept_no, MAX(salary) FROM employee GROUP BY DeptID

As you can see, we don’t need to implement how to calculate the maximum salary (for example, using loops and a variable to track the highest value). We only express what we expect. In Java 8, we can do the same way using streams.

What Is and Is Not a Stream?

  • A Stream is a pipeline of functions that can be evaluated
  • Streams can transform data
  • A Stream is not a data structure
  • Streams cannot mutate data

Most importantly, a stream isn’t a data structure. We can often create a stream from collections to apply a number of functions on a data structure, but a stream itself is not a data structure.

Working With Streams

Obtaining a Stream From a Collection

List<String> items = new ArrayList<String>();

items.add("one");
items.add("two");
items.add("three");

Stream<String> stream = items.stream();


The first list of items is created using the Collection API. Then a Stream of strings is obtained by calling the items.stream() method.

Streams filter() and collect()

Before Java 8, you filtered a List like this

List < String > items = Arrays.asList("one", "two", "three");
List < String > result = new ArrayList < > ();
for (String item: items) {
    if (!"three".equals(item)) { // don't want three
        result.add(item);
    }
}
for (String temp: result) {
    System.out.println(temp); //output : one, two
}


Using Java 8 streams, we can use stream.filter() to filter a List and collect() to convert a stream into a List.

List<String> items = Arrays.asList("one", "two", "three");

List<String> result = items.stream() // obtain a stream from the list
    .filter(item -> !"three".equals(item)) // don't want three
    .collect(Collectors.toList()); // collect the output and convert streams to a List

result.forEach(System.out::println); //output : one, two

Streams map()

Before Java 8:

List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");

List <String> alphaNumbersUpperCase = new ArrayList < > ();
for (String s: alphaNumbers) {
    alphaNumbersUpperCase.add(s.toUpperCase());
}

System.out.println(alphaNumbers); //[one, two, three, four]
System.out.println(alphaNumbersUpperCase); //[ONE, TWO, THREE, FOUR]


Using Java 8's stream.map():

List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");

List<String> alphaNumbersUpperCase =
    alphaNumbers.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); //[ONE, TWO, THREE, FOUR]


Streams sorted()

Using the same example above, we will sort the alphaNumbers:

List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");

List<String> alphaNumbersUpperCase = alphaNumbers.stream()
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); // [FOUR, ONE, THREE, TWO]


To sort in reverse order:

List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");

List<String> alphaNumbersUpperCase = alphaNumbers.stream()
    .map(String::toUpperCase)
    .sorted(Comparator.reverseOrder())
    .collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); // [TWO, THREE, ONE, FOUR]


Conclusion

The Streams API is powerful and simple to understand. It allows us to reduce a huge amount of boilerplate code, create more readable programs, and improve productivity when used properly. We should not leave instantiated streams unconsumed, as that will lead to memory leaks. Apply the close() method or a terminal operation to close the stream.

Stream (computing) Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Thread-Safety Pitfalls in XML Processing
  • Java Stream API: 3 Things Every Developer Should Know About
  • Understanding Lazy Evaluation in Java Streams
  • Exploring TakeWhile and DropWhile Functions in Java

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!