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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. Languages
  4. Working With Stream APIs in Java 1.8

Working With Stream APIs in Java 1.8

Want to learn more about working with Stream APIs in Java 1.8? Check out this tutorial to learn more about the Java Stream concepts in this post.

Rohit upadhyay user avatar by
Rohit upadhyay
·
Oct. 31, 18 · Presentation
Like (6)
Save
Tweet
Share
14.40K Views

Join the DZone community and get the full member experience.

Join For Free

The Stream concept was introduced in Java 1.8 and remains present in the java.util.stream package. It is used to process the object from the collection or any group of objects or data source. We can easily understand the Java stream concept by its name. For example, in a stream, water flows from one water source to a destination. We can perform operations like filtering, collecting, etc. via a stream to get useful water flow. It is the same when working with Java streams. We think that an object flows from one object source to its destination through Stream pipelines. Keep in mind: a stream pipeline is composed of a stream source, zero or more intermediate operations, and a terminal operation. Let's take a closer look!

We should be familiar with a few basic concepts before going any further. Remember one thing: Streams don’t actually store elements; they are computed on demand.

1. C.stream()  — We are going to get a stream object where C is the collection object.

2. filter()  — This is used to perform filtering based on a predicate. The predicate is nothing but a boolean condition. Basically, it is a functional interface and can be replaced by a lambda expression.

3. collect() — This is a terminal operation used to collect filtered or mapped data. For example, check out the following:

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(0);
arrayList.add(10);
arrayList.add(20);
arrayList.add(5);
arrayList.add(15);
arrayList.add(25);
System.out.println(arrayList);


The output will be [0,10,20,5,15,25]. Now, we want to get a new ArrayList of integers, which contains only even integers from the existing ArrayList object. Here, we will demonstrate how we process a collection object without the stream concept.

List<Integer> list = new ArrayList<Integer>();
for(Integer i:arrayList){
if(i%2 == 0)
list.add(i);
}
System.out.println(arrayList);


The output will be [0,10,20].

With the stream concept, it will look something like the following:

List<Integer> list = arrayList.stream().filter(i->i%2==0).collect(Collectors.toList());
System.out.println(arrayList);


For this code, the output will be [0,10,20]. In a collection, we will perform the bulk operation, which is highly recommended for using streams.

Let's take a look at some other useful methods for implementing Streams.

4. map() — For every object, if we want to perform an action and want a result object, then we use the Map method. If we want to increase all the ArrayList data by five, then we can use this function:

List<Integer> l = arrayList.stream().map(i-> i+5).collect(Collectors.toList());


It always takes the functional interface (an interface that contains only one interface), so we can replace it with the lambda expression.

5. count() — We can use this to count how many objects are there in stream ( not in data source).

long noOfEvenInteger = arrayList.stream().filter(i-> i%2!=0).count();


6. sorted() — We use this method to perform sorting in ascending order.

List<Integer> l = arrayList.stream().sorted().collect(Collectors.toList()); return an ascending order list.


For customization, we go to the comparator concept. The comparator is also on the functional interface, so we can also replace it with a lambda expression.

The Comparator contains the compare() method, and we can replace it with the lambda expression compare (obj1, obj2)- return -ve if obj1 has to come before obj2, return +ve if obj1 has to come after obj2, and return 0 if both are equal.

We perform sorting in descending order here and compare method (i1, i2)-> (i1<i2)?1:(i1 > i2)?-1:0. We compare two objects: i1 and i2. If i1 is smaller than i2, it means i1 has to come before i2. So, it will return +ve, or else, it will check to see if i1 is bigger or not. If yes, it means i1 has to come after i2. Then, it will return -ve, and if both are equal, then it will return 0.

List<Integer> list = arrayList.stream().sorted((i1,i2)->(i1, i2)-> (i1<i2)?1:(i1 > i2)?-1:0).collect(Collectors.toList());

7> forEach() - for every element if we want to perform some functionality.

arrayList.stream().forEach(System.out::println);

it will print all object.We can call our own method also.

Consumer<Integer> fun = i->{System.out.println("square of"+i+"is = "+(i*i))};
arrayList.stream().forEach(fun);


8.  toArray() — We use this to convert a stream of an object into an array.

Integer[] arr =arrayList.stream().toArray(Integer::new);


9. Stream.of(arr) — We use this to get a stream from an array or another group of data:

Stream s = stream.of(10,1,2,12,34);
s.forEach(System.out::println);


Stream (computing) Java (programming language) Object (computer science) Concept (generic programming)

Published at DZone with permission of Rohit upadhyay. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • AWS Cloud Migration: Best Practices and Pitfalls to Avoid
  • Beginners’ Guide to Run a Linux Server Securely
  • Promises, Thenables, and Lazy-Evaluation: What, Why, How
  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: