Beautify for loop using stream and lambda

java 8 break out of stream
convert for loop to stream java 8
java 8 foreach return
java stream for loop
java stream foreach
java stream takewhile
java 8 foreach if condition
how to return from stream

Currently I got this code:

    public Iterable<Article> getAllArticle(){
        ArrayList<ArticleEntity> articleEntities = Lists.newArrayList(articleProviderComponent.getAllArticle());
        ArrayList<Article> articles = Lists.newArrayList();
        for(ArticleEntity articleEntity : articleEntities){
        return articles;

The repository returns an Iterable, which I want to convert to a ArrayList. Beside that I want to convert each Entity to a POJO.

I tried using something like list.foreach(ArticleMapper::ArticleMapper.articleEntity2Article) which works fine, but does not return a new list.

A simple map will do the job:

List<Article> articles =

map converts each element to something else using the method given.

How to Break from Java Stream forEach, Java Streams are often a good replacement for loops. Where First, we'll get the Spliterator from our stream, then we'll decorate it with our  Java has fancy methods that make optimal use of streams and lambda expressions. With streams and lambda expressions, you can create an assembly line. The assembly-line solution uses concepts from functional programming. The assembly line consists of several methods. Each method takes the data, transforms the data in some way or other, and hands its …

Stream the List, map it to your target type and collect to a List:

List<Article> articles =;

How Java 8 Lambdas and Streams Can Make Your Code 5 Times , How do Java 8 lambdas and streams perform compared to Sometimes using a simple loop with an iterator is better than getting lambdas and streams Java 8 exceptions have never been so beautiful – Try Takipi for Java 8. You can create a list of lambdas in a python loop using the following syntax − Syntax def square(x): return lambda : x*x listOfLambdas = [square(i) for i in [1,2,3,4,5]] for f in listOfLambdas: print f() Output. This will give the output − 1 4 9 16 25. You can also achieve this using a functional programming construct called currying. example

Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.

According to JavaDoc Collecotrs.toList

Returns a Collector that accumulates the input elements into a new List. There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

The returned articles are of type ArrayList<ArticleEntity>. Thus this list is e.g. mutable.

The return type of the method getAllArticle() is Iterable<Article>. Thus we can call

Iterator<Article> iterator = getAllArticle().iterator(); 

But if you need to call iterator.remove() "there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)

UnsupportedOperationException - if the remove operation is not supported by this iterator

To keep the behaviour of the original code use Collectors.toCollection:

List<Article> articles =

This will return articles built by Lists.newArrayList().

Replace For-Loop with Stream::forEach, loops (for-each-loops) with an invocation of '' method and passes the body of the for-loop as a lambda Consumer parameter. Sometimes using a simple loop with an iterator is better than getting lambdas and streams into the mix. Even if it means writing a few more lines of code and skipping on that sweet syntactic sugar. Using iterators or a for-each loop is the most effective way to go over an ArrayList. Twice as better than a traditional for loop with an index int.

As Iterable is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport you can generate a stream from the Iterable instance and reduce the amount of operations to one:

final List<Article> articlesList =, false)            

Java 8 Features with Examples, For example, we can write above implementation using lambda expression as: Collection interface has been extended with stream() and parallelStream() default methods to get the Stream for I have tried to display the value of a variable using the forEach loop using sysout, no output is displayed. A beautiful Updation. Stream forEach() method in Java with examples Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.

Java 8 Lambda Expressions Tutorial with Examples, Stream interface comes with tons of useful methods which can be used along with lambda expression to do some voodoo. We passed a lambda  If we don't require a stream but only want to iterate over a collection, the first choice should be using forEach() directly on the collection. The source code for the examples in this article is available over on GitHub.

Walking Recursive Data Structures Using Java 8 Streams, The Streams API is a real gem in Java 8, and I keep finding more or less unexpected uses for them. I recently wrote about using them as  Using entrySet() is slightly safer, esp for debugging, as it will is give you matching key/values even if a) hashCode/equals are broken, or more likely b) the map is modified while you are using it.

A Guide to Streams in Java 8: In-Depth Tutorial With Examples, And we can create a stream from individual objects using Stream.of(): forEach() is simplest and most common operation; it loops over the stream elements, This value is passed as input to the lambda, which returns 4. That normaly works good but if you use a loop variable within the a lambda and compile it with a c# 4.0 compiler you get a worng result. In the following code segment i build ten lambdas including the loop variable. That means a closure is build for every lambda. I save the lambdas to the list and when the loop ends i execute the ten lambdas.