Java 8 : Working of streams

When I first heard of a stream, every body was comparing it with the Collection api, So the picture which was there on my mind was that , it is a new kind of data structure introduced in java.But streams are not the data structure.Streams provides methods using which we can perform multiple operations by pipe lining it to produce the desired result.streams are providing results in lazy manner.

Streams is the best feature, java has introduced till now.With the usage of streams so many things in development are easy.But before understanding streams let's see what kind of problem was there in traditional approach.Let's consider below scenario and how does it can be solved using traditional approach and how it can be solved with streams.
Problem Statement
There is a list,containing an employee object.In the employee class there are certain fields defined.Fields like name,age,salary and designation.This list contains duplicate objects also.Now we need a list of employees whose salary are more than 30,000/- Rs.

Below is how we can solve it using traditional approach.

 
                
List<employee> emplaoyeeList = getEmployeeList();
  
  List<employee> resultList = new ArrayList<>();
  for(int i=0;i<emplaoyeelist .size="" emplaoyeelist.get="" getsalary="" i="" if=""> 30000 && !resultList.contains(emplaoyeeList.get(i))) {
    resultList.add(emplaoyeeList.get(i));
   }
  }

Now, let's see the code for solving the same problem using streams.
 
List<employee> emplaoyeeList = getEmployeeList();
  List<Employee> resultList = emplaoyeeList.stream().
             distinct()
              .filter(e -> e.getSalary()>30000).
                collect(Collectors.toList());

As its visible, the code is much smaller for the same things.There might be certain logical diferrence between the logic for traditional approach.But even the best logic will not be able to bit streams.In case of streams we just need to call certain methods for filtering out the results and that's it.We have seen some basic things on streams ,Now lets see the kind of operations which we can perform on streams.


Intermediate Operations

Intermediate operation returns the object of stream type only,The reason is that,by pipe lining the results we can perform multiple operations.

sorted 

sorted method is used for sorting the stream.
Example:
 
List<string> letters = Arrays.asList("B","A","C");
List<string> result = letters.stream().map(x->x+" : "+x).collect(Collectors.toList());
System.out.println(result);

Output:
[A, B, C]

map

map method is used for mapping an object in different one based on predicate passed in to it.
Example:
 
 List<string> letters = Arrays.asList("B","A","C");
  List<string> result = letters.stream().map(x->x+" : "+x).collect(Collectors.toList());
  System.out.println(result);
Output:
[B : B, A : A, C : C]

filter

filter method is used for filtering the stream, based on certain parameter.
Example:
 
  List<String> letters = Arrays.asList("B","BigSize","C");
  List<String> result = letters.stream().filter(x -> x.length()<2).collect(Collectors.toList());
  System.out.println(result);
Output: [B, C] distinct Using distinct operation we can remove the duplicate element from the stream.Let's see the example. Example:
 
List<String> mychar = new ArrayList<String>();
  mychar.add("A");
  mychar.add("B");
  mychar.add("C");
  mychar.add("A");
  mychar.add("F");
  System.out.println(mychar.stream().distinct().count());
Output:
                 4
Terminal Operations

Using terminal operations we can get the resultant type of object.For example list of string.In terminal operation result type will not be of stream.

collect

After performing the operations on collection, if we want the resultant object as collection in that case we can use the collect.
Example:
 
List<String> letters = Arrays.asList("B","BigSize","C");
  List<String> result = letters.stream().filter(x -> x.length()<2).collect(Collectors.toList());
  System.out.println(result);
Output:
[B, C]

forEach

This method is used when we want to iterate element of  the stream.For printing each element of print.
Example:
 
  List<String> lettersForEach = Arrays.asList("B","BigSize","C");
  lettersForEach.stream().forEach(x->{
     System.out.println(x);
  });

});
Output:
B
BigSize
C

reduce

reduce method is taking BinaryOperator as parameter.This is bit difficult to explain.By looking at the code and its output, people will get more idea on that.So let's take a look over that.

Example:

 
List<String> reduceChar = new ArrayList<String>();
    reduceChar.add("A");
    reduceChar.add("B");
    reduceChar.add("C");
    reduceChar.add("D");
    reduceChar.add("F");
    Optional<String> reduced = reduceChar.stream().reduce((s1, s2) -> {
            System.out.println(s1 +" : "+s2);
            return s2;
    });
    System.out.println(reduced);

Output:

A : B
B : C
C : D
D : F
Optional[F]

count

Using count operation we can count the number of element inside stream.Let's consider an example where we want count of distinct element.

Example:
 
List<String> countStream = new ArrayList<String>();
  countStream.add("A");
  countStream.add("B");
  countStream.add("C");
  countStream.add("A");
  countStream.add("F");
  System.out.println(countStream.stream().distinct().count());
Output: 
                4

Share this:

CONVERSATION

0 comments:

Post a Comment