Java Stream filter custom object by attribute

Description

Java Stream filter custom object by attribute

import java.util.Arrays;
import java.util.List;

public class Main
{
   public static void main(String[] args)
   {// ww  w. ja  va  2  s . c o  m
      Language[] langArray = {
         new Language("CSS", 51321),
         new Language("HTML", 72310),
         new Language("Java", 43287.5),
         new Language("Javascript", 47100.77),
         new Language("C++", 62121),
         new Language("C", 32251),
         new Language("SQL", 42361.4)};

      List<Language> langList = Arrays.asList(langArray);

      langList.stream().forEach(System.out::println);
      
      langList
          .stream()
          .filter(e -> e.getFirstName().startsWith("Java"))
          .forEach(e -> System.out.println(e.getSalary()));

   } 
}
class Language
{
   private String firstName;
   private double salary; 
   
   // constructor 
   public Language(String firstName, 
      double salary)
   {
      this.firstName = firstName;
      this.salary = salary;
   } 
   // get firstName
   public String getFirstName()
   {
      return firstName;
   }

   // get salary
   public double getSalary()
   {
      return salary;
   }

   // return a String containing the Employee's information
   @Override
   public String toString() 
   {
      return String.format("%-20s %8.2f", 
         getFirstName(), getSalary());
   } 
}



PreviousNext

Related