Java Lambda Expression Method References to Instance Methods get object attribute value

Description

Java Lambda Expression Method References to Instance Methods get object attribute value


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

public class Main
{
   public static void main(String[] args)
   {/*w ww .  j av a2s .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);
      
      // sum of salaries with DoubleStream sum method
      double sum = langList.stream().mapToDouble(Language::getSalary).sum();
      System.out.println(sum);

   } 
}
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