Sunday, July 14, 2019

Stream API Examples

Q- How to create stream in java 8?
There are number of ways to create steram in java.
  • Stream from an array
  • Stream from an list
  • Stream from individual objects using Stream.of()
  • Using Stream.builder()
  • Stream myStream = Arrays.stream(myArray);
In below Examples you will see how to create stream and use methods of stream in java 8.


package com.shubh.stream.list.to.map;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class StreamMethodExample {

 public static void main(String[] args) {

  String[] myArray = new String[]{"Amar", "Aman", "Kuldeep"};
  // Create stream then sort and collect in list"
  System.out.println(" // Create stream and sort then collect in list");
  List list = Arrays.stream(myArray).sorted().collect(Collectors.toList());
  list.forEach(s -> System.out.println(s));
  
  // Create stream then sort and print
  System.out.println(" // Create stream and sort then print");
  Arrays.stream(myArray).sorted().forEach(s -> System.out.println(s));

  // Create stream using list example
  System.out.println("// Create stream using list example ");
  List items = new ArrayList();
  items.add("Arun");
  items.add("Tarun");
  items.add("Pradeep");
  Stream stream = items.stream();

  // Stream concat() example
  System.out.println("// Stream concat() example ");
  List list1 = Arrays.asList("Raj", "Kumar", "Gupta");
  List list2 = Arrays.asList("Deepak", "Kamal", "Sandeep");
  Stream resStream = Stream.concat(list1.stream(), list2.stream());
  resStream.forEach(s -> System.out.println(s));

  // Stream count() example
  System.out.println("// Stream count() example");
  List list = Arrays.asList("Amar", "Aman", "Kuldeep");
  Predicate predicate = s -> s.startsWith("A");
  long startWithA = list.stream().filter(predicate).count();
  System.out.println("Number of Matching Element:" + startWithA);

  // Stream sorted() example
  System.out.println("// Stream sorted() example ");
  List listToSort = Arrays.asList("Suresh", "Amit", "Boby");
  listToSort.stream().sorted().forEach(s -> System.out.println(s));

  // Stream distinct() example
  System.out.println("// Stream distinct() example ");
  List list3 = Arrays.asList("AAA", "AAA", "BBB");
  long elementCount = list3.stream().distinct().count();
  System.out.println("Number of distinct element:" + elementCount);
 }
}
Output of above program.

// Create stream using list example 
// Stream concat() example 
Raj
Kumar
Gupta
Deepak
Kamal
Sandeep
// Stream count() example
Number of Matching Element:2
// Stream sorted() example 
Amit
Boby
Suresh
// Stream distinct() example 
Number of distinct element:2
We can obtain a stream in different ways.

package com.shubh.stream.api;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamCreation {

 public static void main(String[] args) throws ParseException {

  SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");

  Employee arrayOfEmps[] = { new Employee(1, "C", 30, "C@xyz.com", formatter.parse("01/08/1999"), 15000),
    new Employee(2, "A", 40, "A@xyz.com", formatter.parse("01/08/1955"), 5000),
    new Employee(3, "A", 10, "A1@xyz.com", formatter.parse("01/08/1979"), 3000),
    new Employee(3, "A", 10, "A2@xyz.com", formatter.parse("01/08/1978"), 2000),
    new Employee(4, "B", 20, "B@xyz.com", formatter.parse("01/08/1989"), 2000),
    new Employee(5, "E", 50, "E@xyz.com", formatter.parse("01/08/1985"), 10000) };

  // stream from an array:
  Stream.of(arrayOfEmps);

  // stream from an list:
  List empList = Arrays.asList(arrayOfEmps);
  empList.stream();

  // stream from individual objects using Stream.of():
  Stream.of(arrayOfEmps[0], arrayOfEmps[1], arrayOfEmps[2]);

  // using Stream.builder():
  Stream.Builder streamBuilder = Stream.builder();
  streamBuilder.accept(arrayOfEmps[0]);
  streamBuilder.accept(arrayOfEmps[1]);
  streamBuilder.accept(arrayOfEmps[2]);
  Stream employeeStream = streamBuilder.build();
 }
}
Map() And Filter() Example

package com.shubh.stream.comparator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CreateStreamApp {
public static void main(String args[]) {
        
        List myList = new ArrayList();
        myList.add("AAA");
        myList.add("AaA");
        myList.add("aAk");
        
        // Here first it will filter "start with lowercase "a" character then convert into uppercase
        System.out.println("// Here first it will filter startsWith('a') character then convert into uppercase");
        List startWithLowerCase_A_ThenConvertToUpperCase = myList.stream().filter(item->item.startsWith("a")).map(item -> item.toUpperCase()).collect(Collectors.toList());
        startWithLowerCase_A_ThenConvertToUpperCase.forEach(s->System.out.println(s));
        
        // Here fisrt it conver to uppercase then filter--- start with lowercase "a". So there is no output. because there is no lower case character in stting after map operation.  
        System.out.println("// Here fisrt it conver to uppercase then filter--- startsWith('a').So there is no output. because there is no lower case character in stting after map operation.");
        List resultList = myList.stream().map(item -> item.toUpperCase()).filter(item->item.startsWith("a")).collect(Collectors.toList());
        resultList.forEach(s->System.out.println(s));
        
         // Here fisrt it conver to uppercase then filter--- start with uppercase "A".
         System.out.println(" // Here fisrt it conver to uppercase then filter--- startsWith('A').");
        List resultList1 = myList.stream().map(item -> item.toUpperCase()).filter(item->item.startsWith("A")).collect(Collectors.toList());
        resultList1.forEach(s->System.out.println(s));
    }
}

Output of above program.

// Here first it will filter startsWith('a') character then convert into uppercase
AAK
// Here fisrt it conver to uppercase then filter--- startsWith('a').So there is no output. because there is no lower case character in stting after map operation.
 // Here fisrt it conver to uppercase then filter--- startsWith('A').
AAA
AAA
AAK


Related Tutorial

No comments:

Post a Comment