Java Stream map custom objects

Introduction

The following code uses map() to create a new stream.

It contains only selected fields from the original stream.

import java.util.ArrayList;
import java.util.stream.Stream;

class NamePhoneEmail {
  String name;/*from ww  w . java 2 s.  c om*/
  String phonenum;
  String email;

  NamePhoneEmail(String n, String p, String e) {
    name = n;
    phonenum = p;
    email = e;
  }
}

class NamePhone {
  String name;
  String phonenum;

  NamePhone(String n, String p) {
    name = n;
    phonenum = p;
  }
}

public class Main {

  public static void main(String[] args) {

    // A list of names, phone numbers, and e-mail addresses.
    ArrayList<NamePhoneEmail> myList = new ArrayList<>();

    myList.add(new NamePhoneEmail("CSS", "555-5555", "css@demo2s.com"));
    myList.add(new NamePhoneEmail("HTML", "555-4444", "html@demo2s.com"));
    myList.add(new NamePhoneEmail("Java", "555-3333", "java@demo2s.com"));

    System.out.println("Original values in myList: ");
    myList.stream().forEach((a) -> {
      System.out.println(a.name + " " + a.phonenum + " " + a.email);
    });
    System.out.println();

    // Map just the names and phone numbers to a new stream.
    Stream<NamePhone> nameAndPhone = myList.stream().map((a) -> new NamePhone(a.name, a.phonenum));

    System.out.println("List of names and phone numbers: ");
    nameAndPhone.forEach((a) -> {
      System.out.println(a.name + " " + a.phonenum);
    });
  }
}



PreviousNext

Related