Java Stream map to choose single field from an object

Description

Java Stream map to choose single field from an object

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));
    //www  .  j  a  v a  2  s .  co 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