Java Stream filter custom object by attribute via instance method reference

Description

Java Stream filter custom object by attribute via instance method reference

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

public class Main
{
   public static void main(String[] args)
   {//from   ww  w .j a v  a 2 s .  c  o m
      Language[] langArray = {
         new Language("CSS",  55555),
         new Language("HTML", 66666),
         new Language("Java", 44444.5),
         new Language("Javascript", 77777.77),
         new Language("C++", 88888),
         new Language("C", 33333),
         new Language("SQL", 99999.4)};

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

      langList.stream().forEach(System.out::println);
      
      langList
          .stream()
          .filter(Language::isClientSide)
          .forEach(e -> System.out.println(e.getSalary()));

   } 
}
class Language
{
   private String firstName;
   private double salary; 
    
   public Language(String firstName, 
      double salary)
   {
      this.firstName = firstName;
      this.salary = salary;
   } 
   public boolean isClientSide() {
      if("HTML".contentEquals(this.getFirstName())) {
         return true;
      }
      return false;
   }
   public String getFirstName()
   {
      return firstName;
   }

   public double getSalary()
   {
      return salary;
   }

   @Override
   public String toString() 
   {
      return String.format("%-20s %8.2f", 
         getFirstName(), getSalary());
   } 
}



PreviousNext

Related