Java Stream API

Nov 11th 2020


Java logo

Java and Functional Programming

Java is one of the godfathers of object-oriented programming. Java got its start with print servers, and is still very popular to this day. With applications run on the Java Virtual Machine(JVM), Developers use Java for applications across the spectrum, from Android to enterprise.

Functional programming, in contrast to object-oriented programming, an application application is composed of mathematically pure functions. You can read more about object-oriented vs functional programming here. Functions are first class members in functional programming, they are the equivalent of objects that can be passed around a common variable.

Lambda Expressions and Anonymous Functions

Anonymous functions are essentially functions without names. Lambda expressions are short hand for a anonymous function declaration. They can usually be noted for some kind of arrow syntax.

Java 8, along with other things(including the Stream API), brought us lambda expressions and somewhat easier ways to run operations asynchronously.

Lambda Syntax

In Java, the lambda expression for an anonymous function of return type void that takes no arguments, would like something like this


() -> {
  //do something
  //return nothing
}

This is the equivalent to


void anonFunction() {
  //do something
  //return nothing
}

This is the oneAdder method


int oneAdder(int addOneToMe){
  return addOneToMe + 1;
}

The lambda syntax for this is


(int addOneToMe) -> {
  return addOneToMe + 1;
}

Lambda and Asynchronous Processing

You might notice that our first lambda example


() -> {
  //do something
  //return nothing
}

Has something in common to the Runnable interface, it has the same signature as the Runnable.run() method


public void run();

We can use the Runnable interface as a functional interface(a topic for another post) to pass these lambda syntax anonymous functions around as first class members.

Back to asynchronous processing, if we look at the execute method of the Executor interface


  public synchronized void execute(Runnable r);

Now we can pass the execute method a lambda expression to run in another thread


Executor executor = Executors.newSingleThreadExecutor();

executor.execute(() -> {
  //do something in another thread
  //return nothing
}); 

Java Stream API

Java 8 brought us the Stream API. The Stream API allows us to process collections in a more streamlined, syntactically cleaner fashion. The stream package provides us with a tool belt full of methods for processing collections.

A collection can be turned into a stream by calling the new stream() method.

Stream Methods

The Stream API provides quite a few handy methods, but we will concentrate on the most ones.

map

The map methods is used when you want to return a new object(can be different type) for each element in the stream.


List<String> phrases = new ArrayList<>(aPopulatedList);

List<Integer> charLengths = phrases.stream().map(String phrase -> {
  return new Integer(phrase.toCharArray().length); 
});

This is equal to


List<Integer> charLengths = new ArrayList<>();
for(String phrase : phrases){
  charLengths.add(phrase.toCharArray().length); 
}

filter

Filter allows us to remove elements from the stream, by returning a boolean value.


charLengths.stream().map(Integer length -> {
  return length > 5;
});

This is equal to

List<Integer> filteredLengths = new ArrayList<>();

for(Integer length : charLengths){
  if(length > 5){
    filteredLengths.add(length);
  }
}

forEach

Last but not least, forEach is the simplest case


charLengths.stream().forEach(Integer length -> {
  length.add(1);
});

Which equals


for(Integer length : charLengths){
  length+= 1;
}

Chaining

We can chain stream operations together to do more complex transformations of collections


aList.stream()
  .filter(element -> {
    //remove elements
  })
  .map(element -> {
    //transform elements
  })

Conclusion

So this is a micro breakdown of the Stream API to get you going. The Stream API allows us to replace our ugly for loops with much easier to read lambda expressions.

Comments


03/27/2021 05:09


?t's awesome t? pay ? visit t?is website and reading the views of ?ll friends on t?e tolpic oof this piece ?f writing, while I am al?o eager of getting ?now-how. Wo?ld Yo? Also visit my website; situs togel online Terbaik


03/24/2021 17:23


It's an amazing paragraph iin favor of all the web users; thedy will get benefit from it I am sure. Potenzmittel ohhne Vorauszahlung web site dapoxetin bestellen


03/21/2021 04:38


?? ?? recommended information community site Yamap


03/10/2021 13:17


I do not even know the way I ended up here, but I believed this publish was once great. I don't know who you might be but certainly you're going to a well-known blogger when you are not already. Cheers! pkv games


03/06/2021 15:04


I got this web page from my buddy who told me concerning this website and now this time I am visiting this web site and reading very informative articles or reviews at this place. paten99


02/27/2021 16:35


??? ??? ?? ??? ???? ?? ???? ?? ??? ????.


02/26/2021 17:06


I'm truly enjoying the design and layout of your blog. It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Great work! PKV


02/19/2021 23:53


Awesome post. bandarqq


02/16/2021 16:05


I am sure this article has touched all the internet users, iits really really good piece of writing on building up new weblog. ?????????? ?????? ???? homepage ???????????????


02/15/2021 00:34


gookerdoughboy777 https://gookerdoughboy777.blogspot.com It's amazing to visit this web page and reading the views of all mates concerning this piece of writing, while I am also zealous of getting experience.


02/14/2021 16:47


Heya i am for the primary time here. I found this board and I in finding It truly helpful & it helped me out much. I am hoping to provide something back and aid others such as you aided me. situs judi online


02/13/2021 04:14


I do not even know how I ended up here, butt I thought this posxt was good. I don't know who you are but definitely you aree going to a famous blogger if you aren't alkready ;) Cheers! ??????????? ???? web page ?????????? ???????? ???????


02/12/2021 16:18


This website was... how do I say it? Relevant!! Finally I have found something that helped me. Thank you! ?????? homepagye Coinbase


02/10/2021 19:06


I do not even know how I ended up right here, but I thought this post was once great. I do not recognize who you are but certainly you're going to a well-known blogger for those who aren't already. Cheers! Akb web site ??????????? ?????????????


02/09/2021 22:37


Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how could we communicate? situs judi


02/06/2021 16:11


Remarkable! Its actually awesome paragraph, I have gott much clear idea about from thos post. Extra Super Test Paccchetto website ordinare kamagra oral jelly


02/05/2021 16:51


Fabulous, what a blog itt is! This blog provides useful facts to us, keep it up. ?????? ??? ????? web page ????? ?????? ??? ???????


02/03/2021 20:20


Hi there! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us valuable information to work on. You have done a outstanding job! bandarqq


01/31/2021 09:18


Thanks to my father whho stated too me onn the topic off this webpage, this web site is genuinely amazing. ????? ? ??????? web page ??????? ?????


01/28/2021 09:14


Good web site you have here.. It's difficult to find high quality writing like yours nowadays. I honestly appreciate individuals like you! Take care!! situs judi


01/26/2021 10:19


Apple Watch has a dazzling and vivid OLED display which offers decent visibility outdoors. The glass is durable and can easily bear drops and falls. amazing apple watch giveaway


01/25/2021 05:08


A fascinating discussion is definitely worth comment. I do believe that you ought to write more on this subject, it may not be a taboo subject but typically people do not speak about these topics. To the next! Kind regards!! PKV


01/22/2021 20:23


Thanks for the auspicious writeup. It in fact used too be a entertaihment account it. Glance advahced to more added agreeable from you! However, how can we keep up a correspondence? ?????? ???? ? ????????? homepage BCR ?????? ??????????? ? ?????


01/22/2021 07:42


I just could not leave your web site before suggesting that I actually enjoyed the standard information an individual supply forr your visitors? Is gonna be again regularly to cyeck out new posts ???-?????? site GRAN Test System


01/19/2021 19:34


Wow! In th? end I g?t a weblog from where I can re?lly get valuable data conce?ning my study and knowledge. Would You Check out my blog :: Game slot Online


01/16/2021 21:54


aurogra generic vs levitra


01/16/2021 03:36


Excellent, what a ebpage it is! This weblog provides useul facts to us, keep it up. Mooto g4 play ????? weboage amazfit


01/09/2021 07:57


I go too see everyday some weeb pages andd information sites to read articles, however this blog presents feature based posts. ?????? ????? web page ???????????? ????????


01/03/2021 14:57


I wanted to thank you for this very good read!! I definitely enjoyed every bit of it. I have got you bookmarked to look at new stuff you post??¦ Vigra 25mg site ordibare Cialis Professional


01/03/2021 06:10


WOW just what I was searchbing for. Came here by sewrching for honda ??????? honda safety driving homepage ?????????? ????? ???????


01/02/2021 00:17


Youu actually explained that fantastically. Best Essay writing write my essay


12/31/2020 17:45


You've made your position quite well.. Best Essay writing buy essay papers cheap


12/21/2020 07:55


Fantastic forum posts, Regards! Best Essay writing write my essay cheap


12/15/2020 12:14


Hello, everything iis going perfectly here and ofcourse every one is sharing data, that's genuinely good, keep up writing. Igmarkets webpage option888


12/11/2020 01:20


Hi it's me, I am also visiting this site regularly, this site is truly nice and the people are truly sharing nice thoughts. ?????? ??????????????? ?????? homepage ??????? ??????????????? ?????? ????


12/06/2020 10:36


Wonderful forum posts. With thanks. Best Essay writing buy essays online


12/05/2020 10:46


Truly plenty of fantaastic data! Best Essay writing paper writing service


12/05/2020 09:54


Regards! I like it. Beest Essay writing buy essay ppapers cheap


11/28/2020 06:00


Good way of telling, and pleasant post to take facts regarrding my presentation subject matter, which i am going to deliver in university. ????? ????????????? ?????? ? ????? web site ????????


Navagation