How to use collect(Supplier supplier, ObjIntConsumer accumulator, BiConsumer combiner)

Here is an example to explain how to use collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner).

Syntax:

Modifier and Type               Method
<R> R                           collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner)
package com.nourit.java8.Streams.IntStream;

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

public class IntStreamCollect {

  public static void main(String[] args) {
    System.out.println("---------- Collectors Example 1 -----------------");
    List<Integer> sourceLongList1 = Arrays.asList(1, 10, 50, 80, 100, 120, 133, 333);
    //Performs a mutable reduction operation on the elements of this stream.
    List<Integer> collect1 = sourceLongList1.stream().filter(l -> l >= 100).collect(ArrayList::new, List::add, List::addAll);
    for (Integer value : collect1){
      System.out.println(value);
    }
    System.out.println("---------- Collectors Example 2 -----------------");
    List<Integer> sourceLongList2 = Arrays.asList(1, 10, 50, 80, 100, 120, 133, 333);
    List<Integer> collect2 = sourceLongList2.stream().filter(l -> l >= 100).collect(Collectors.toList());
    for (Integer value : collect2){
      System.out.println(value);
    }
    System.out.println("---------- Collectors Example 3 -----------------");
    List<Integer> sourceLongList3 = Arrays.asList(1, 10, 50, 80, 100, 120, 133, 333);
    List<Integer> collect3 = sourceLongList3.stream().filter(l -> l >= 100).collect(Collectors.toCollection(ArrayList::new));
    for (Integer value : collect3){
      System.out.println(value);
    }
    System.out.println("---------------------------------------");
  }
}

Output:

---------- Collectors Example 1 -----------------
100
120
133
333
---------- Collectors Example 2 -----------------
100
120
133
333
---------- Collectors Example 3 -----------------
100
120
133
333
---------------------------------------

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*