Java Stream collect to List

Introduction

To get a collection from a stream, use the collect() method.

The following code shows how to use collect() to create a List and a Set from a stream.

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class NamePhoneEmail {
  String name;//w w w  .  j  av  a  2 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));

    // Use collect to create a List of the names and phone numbers.
    List<NamePhone> npList = nameAndPhone.collect(Collectors.toList());

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

    // Obtain another mapping of the names and phone numbers.
    nameAndPhone = myList.stream().map((a) -> new NamePhone(a.name, a.phonenum));

    // Now, create a Set by use of collect().
    Set<NamePhone> npSet = nameAndPhone.collect(Collectors.toSet());

    System.out.println("\nNames and phone numbers in a Set:");
    for (NamePhone e : npSet)
      System.out.println(e.name + ": " + e.phonenum);
  }
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
  public static void main(String args[]) {
    List<Language> langList = Arrays.asList(new Language("CSS",2),
        new Language("HTML",4));
    //from  w w  w  .  ja v a2  s .c  o  m
    System.out.println(langList);
    
    List<String> listNames = langList.stream().map(u -> u.getName())
        .collect(Collectors.toList());
    
    System.out.println(listNames);
  }
}

class Language {
  private String name;
  private int id;
  
  public Language(String name, int i) {
    this.name = name;
    this.id = i;
  }
  
  public int getId() {
    return id;
  }

  public String getName() {
    return this.name;
  }

  @Override
  public String toString() {
    return "Language [name=" + name + ", id=" + id + "]";
  }

}



PreviousNext

Related