Saturday, January 21, 2017

Collection Iterator using Java 8

Method summary of new collection classes:

     1)     asList() takes Object Array and convert to fixed sized List
     2)    forEach(Consumer<? super Person> action) takes implementation of Consumer interface . Consumer interface has accept(T obj)
     3)    filter() takes implementation of Predicate interface. This is a functional interface whose functional method is test(Object).

package com.java8.exercise;

import java.util.Arrays;
import java.util.List;

public class CollectionExample {
     public static void main(String[] args) {

          // Array of Person object
          Person[] person = { new Person("Paras", "Chawla", "Silicon Valley", 25),
                   new Person("Sonal", "Gupta", "USA", 25), new Person("Richa", "Chawla", "Singapore", 29) };

          // Converting Array<Objects> to fixed sized List<Object>
          List<Person> people = Arrays.asList(person);

          // forEach using Lamda expression
          people.forEach(p -> System.out.println(p));
         
          // 1)Collection --Source 2)filter for multiple operation 3) forEach --Terminal Operation
          // stream() is an Internal iteration ...
          people.parallelStream().filter(p-> p.getFirtsName().startsWith("P")).forEach(p->System.out.println(p));
    
     }
}

Output:
Person [firtsName=Paras, lastName=Chawla, address=Silicon Valley, age=25]
Person [firtsName=Sonal, lastName=Gupta, address=USA, age=25]
Person [firtsName=Richa, lastName=Chawla, address=Singapore, age=29]
Person [firtsName=Paras, lastName=Chawla, address=Silicon Valley, age=25]

No comments:

Post a Comment