Java Stream map to int

Introduction

We can map a stream to a primitive type stream via the following method:

DoubleStream mapToDouble(ToDoubleFunction<? super T> mapFunc) 
   IntStream mapToInt(ToIntFunction<? super T> mapFunc) 
  LongStream mapToLong(ToLongFunction<? super T> mapFunc) 

The following code first creates an ArrayList of Double values.

It then uses stream() followed by mapToInt() to create an IntStream that contains the ceiling of each value.

 
import java.util.ArrayList;
import java.util.stream.IntStream; 
 
public class Main { 
 
  public static void main(String[] args) { 
 
    // A list of double values. 
    ArrayList<Double> myList = new ArrayList<>(); 
 
    myList.add(1.9); /*from   w  ww  .j  a  va 2  s .c  o m*/
    myList.add(4.6); 
    myList.add(9.2); 
    myList.add(7.7); 
    myList.add(12.1); 
    myList.add(5.0); 
 
    System.out.print("Original values in myList: "); 
    myList.stream().forEach( (a) -> { 
      System.out.print(a + " "); 
    }); 
    System.out.println(); 
 
    // Map the ceiling of the elements in myList to an InStream. 
    IntStream cStrm = myList.stream().mapToInt((a) -> (int) Math.ceil(a)); 
 
    System.out.print("The ceilings of the values in myList: "); 
    cStrm.forEach( (a) -> { 
      System.out.print(a + " "); 
    }); 
 
  } 
}



PreviousNext

Related