Java Stream collect to LinkedList

Description

Java Stream collect to LinkedList

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

class NamePhoneEmail {
  String name;// w w w .j  a v  a2  s . c  o m
  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"));

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

    LinkedList<NamePhone> npList = nameAndPhone.collect(  
        () -> new LinkedList<>(),  
        (list, element) -> list.add(element),  
        (listA,listB ) -> listA.addAll(listB)); 

    System.out.println("Names and phone numbers in a List:");
    for (NamePhone e : npList)
      System.out.println(e.name + ": " + e.phonenum);

  }
}



PreviousNext

Related