Easy Example Java 8 Streams
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
/***
* PackageName PACKAGE_NAME
* Created by mhafidi on 30/04/2017.
* <p>
* * A simple introduction to using Streams && with Collectors
* * @title Example Java 8 Dubious_1
* * @author MHI
* * @since Jan 27, 2016
**/
//The following example will show you how streams can shrink your code and make it easier to maintain.
public class HelloLambdaExpressionStream
{
final static String ALPHA = "alpha";
private HelloLambdaExpressionStream()
{
}
public static void main(String args[])
{
//let's consider the following string array:
ArrayList<String> lStringList = new ArrayList<>(Arrays.asList("alpha_1", "alpha_2", "beta", "gamma"));
//now, we would like to collect all the strings that contain the expression "alpha" into a new collection.
//1) first solution: a trivial way to that but not very elegant is the following
ArrayList<String> lnewStringList = new ArrayList<>();
for (String lelt : lStringList)
{
if (lelt.contains(ALPHA))
{
lnewStringList.add(lelt);
}
}
//2) second solution: Stream java 8 consideration
ArrayList<String> lnewStringListJava8 = new ArrayList<>(lStringList.stream().filter(t -> t.contains(ALPHA)).
collect(Collectors.toList()));
}
}