Stream to Primitive Stream

Java-Stream to Primitive Stream

Stream to Primitive Stream

The Stream class provides three methods that return a primitive stream from Stream. These three methods are:

Stream to Primitive Stream

Consider the following program, it first creates an Stream of PlayerData. It then uses mapToInt( ) and mapToDouble( ) to create an IntStream and DoubleStream that are contains the each player weight and height. The stream produced by mapToInt( ) contains the each player weight of the elements in plstm. The stream produced by mapToDouble( ) contains the each player height of the elements in plstm.

Program

Stream to Primitive Stream

Program Source

import java.util.stream.Stream;
import java.util.stream.IntStream;
import java.util.stream.DoubleStream;

class PlayerData{
   
    String name;
    int age;
    double height;
    
    PlayerData(String n,int a,double h){
        name = n;
        age = a;
        height = h;
    }
}
public class Javaapp {
    
    public static void main(String[] args) {

        PlayerData pldata[] = {new PlayerData("Logan",85,5.8),
                               new PlayerData("Ethan",95,5.9),
                               new PlayerData("Jacob",90,5.7),
                               new PlayerData("Henry",98,6.2),
                               new PlayerData("Aiden",100,6.1)};
        Stream plstm = Stream.of(pldata);
        IntStream istm = plstm.mapToInt((e)->e.age);
        System.out.print("Each player weight->");
        istm.forEach((e)->System.out.print(e+", "));
        System.out.println();
        
        plstm = Stream.of(pldata);
        DoubleStream dstm = plstm.mapToDouble((e)->e.height);
        System.out.print("Each player height->");
        dstm.forEach((e)->System.out.print(e+", "));
    }
}

Leave a Comment