Learn Stream | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 11

Learn Stream

Someone have a good guide for learn the use of the stream in java or want to explain how to use it?

6th Sep 2017, 11:24 PM
Davide Mazzeo
Davide Mazzeo - avatar
3 Answers
+ 2
Stream is awesome tool in Java 8. You can do numerous things in a single line. Just for an example: If you have a List of Employee objects and you want a list of firstname+lastname: here is the single line code: nameList= employeeList.stream().map(e->e.getFirstName()+getLastName()).collect(Collectors.toList()); Explanation: stream() method of list object returns a stream. map is an "intermediate" method of stream which returns a stream again. In this case it returns a stream of Names (String). There are other intermediate methods like- filter. collect is a terminal method. Which finally makes a list of names out of the stream. You can play with it many ways. Like if you want the names to be uppercased just insert another map: nameList= employeeList.stream().map(e->e.getFirstName()+getLastName()).map(s->s.uppercase()).collect(Collectors.toList()); If you want the names which starts with "sen" put a filter: nameList= employeeList.stream().map(e->e.getFirstName()+getLastName()).filter(s->s.startsWith("sen").collect(Collectors.toList()); Like that. There are infinite possibilities. You can make sum/average in case of numeric data etc. It is assumed that you have idea of Lambda expression.
19th Sep 2017, 7:49 PM
Debapriya Sen
Debapriya Sen - avatar
+ 9
yes i have seen it in a video and it is really good for sort or filter the element of a Collection. i have to exercises more for understand better how to use. thanks for your reply.
19th Sep 2017, 7:55 PM
Davide Mazzeo
Davide Mazzeo - avatar
+ 1
Solo learn should include a Java 8 module for practice. It would be really fun.
19th Sep 2017, 7:58 PM
Debapriya Sen
Debapriya Sen - avatar