Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introduction to Java 8 Streams

DZone's Guide to

Introduction to Java 8 Streams

Use Java 8's Streams to handle multi-core processors and use multiple threads to process your data.

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

In Java 8, we have a new feature called “Streams.” These “Streams” are similar to collections, but there are some differences. Primarily the collections are the data structures which will hold the data. To process the data, we need to get the data from the collections and execute some logic. For example, we have a list of students. We need to sort the students based on the marks secured, in descending order. To perform the above-said logic, we have to follow these steps.

Create a Comparator

package org.smarttechie;

import java.util.Comparator;

public class MarksComparator implements Comparator<Student>{

@Override
public int compare(Student student1, Student student2) {

   if (student1.getTotalMarks() > student2.getTotalMarks()) {
       return -11;
    } else if (student1.getTotalMarks() < student2.getTotalMarks()) {
      return 1;
    } else {
      return 0;
   }
  }
}

Call the Method

 Collections.sort(students, new MarksComparator());

With Streams we can do this in a simple way. The code snippet is given below.

List<String> studentRollNumbers = students.parallelStream().sorted()
                                  .map(Student::getRollNumber)
                                  .collect(Collectors.toList());

Another use case is where we want to get the student whose name is “ABC_4”. If you use the collections approach, we need to iterate the list and compare each student name with “ABC_4”. With the Streams can do it very simply:

boolean studentFound = students.parallelStream()
                                   .anyMatch(t -> t.getStudentName()
                                   .equalsIgnoreCase("ABC_4"));

If you look at the above code, the stream has the flow of data and processes the data on the fly to generate the result. Here, each method acting on a stream is a pipeline. The output of the one pipeline becomes input to the other pipeline. You can get the stream by calling stream() or parallelStream(). If you have a multi-core processor system and want to utilize the CPU, then you can use parallelStream(), which will use multiple threads to process the data. As a developer, you don't need to write multi-thread programming.

The sample code used in this article is available here.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

Topics:
streams ,java 8

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}