Dubious Java 8

What is a Stream

  1. Object which is used to define a set of Operations
  2. The stream doesn't pocess the data on which it executes its operations
  3. The stream doesn't modify the data that is under its treatment 
  4. The stream treats the data on one pass execution
  5. The stream is algorithmically optimized and enabled to be used for parallel executions 

 

Introduction To Lambda Expressions

What is a Lambda?

  • A Lambda is a Function
  • A function is a computation that takes parameters and returns a value
  • Until Java8 , function could only be implemented using methods
  • A lambda enables functions to be passed around or stored like data (which enables to pass lambdas as arguments)

Continue reading

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()));

  }

}