Question

In: Computer Science

from Big Java Early Objects 7th edition Question Declare an interface Filter as follows: public interface...

from Big Java Early Objects 7th edition

Question
Declare an interface Filter as follows:

public interface Filter { boolean accept(Object x); }

Modify the implementation of the Data class in Section 10.4 to use both a Measurer and a Filter object. Only objects that the filter accepts should be processed. Demonstrate your modification by processing a collection of bank accounts, filtering out all accounts with balances less than $1,000.

Solve Exercise •• P10.6, using a lambda expression for the filter.

How would you use a use a lambda expression for the filter class?????
below is working code for the first part of the question, thanks.

*******************************************************************************

Filter.java <- needs to be lambda expression
public interface Filter
{
// this is what sifts through the -1000 and +1000 accounts
boolean accept(Object anObject);
}

below classes for
*******************************************************************************

BalanceFilter.java
public class BalanceFilter implements Filter
{
@Override
public boolean accept(Object object)
{
return ((BankAccount) object).getBalance() >= 1000;
}
}

*******************************************************************************
Measurer .java
public interface Measurer
{   
double measure(Object anObject);
}

*******************************************************************************

public class BankAccount
{
private double balance;
  
public BankAccount()
{
balance = 0;
}
  
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
  
public void deposit(double amount)
{
balance = balance + amount;
}
  
public void withdraw(double amount)
{
balance = balance - amount;
}
  
public double getBalance()
{
return balance;
}
  
public void addIntrest(double rate)
{
balance = balance + balance * rate/100;
}
  
}

*******************************************************************************

DataSet.java
public class DataSet
{

public static double average(Object[] objects, Measurer meas, Filter filt)
{
double sum = 0;
double avg = 0;
int count = 0;
  
for (Object ob : objects)
{
if (filt.accept(ob))
{
sum += meas.measure(ob);
count++;
}
}
  
if (count > 0)
{
avg = (double)sum/count;
}
  
return avg;
}
  
public static void main (String[] args)
{

BankAccount accounts[] = new BankAccount[]
{
new BankAccount(200),
new BankAccount(1500),
new BankAccount(1000),
new BankAccount(2000),
new BankAccount(3000),
new BankAccount(0),
new BankAccount(50),
};
  
BalanceMeasurer measurer = new BalanceMeasurer();
BalanceFilter filter = new BalanceFilter();
  
double avg = average(accounts, measurer, filter);
System.out.println("Average for bank accounts with 1000.00 in collateral is "+avg);
}   
}

*******************************************************************************

BalanceMeasurer.java
public class BalanceMeasurer implements Measurer
{
public double measure(Object object)
{
return ((BankAccount) object).getBalance();
}
  
}

Solutions

Expert Solution

In the below code i have put commnets for the code for the lambda expression for filter

(all the remaining code remains same). Only DataSet.java, Filter.java has the changes.

========================

CODE

======================

DataSet.java

public class DataSet {

   public static double average(Object[] objects, Measurer meas, Filter filt) {
       double sum = 0;
       double avg = 0;
       int count = 0;

       for (Object ob : objects) {
           if (filt.accept(ob)) {
               sum += meas.measure(ob);
               count++;
           }
       }

       if (count > 0) {
           avg = (double) sum / count;
       }

       return avg;
   }

   // main method
   public static void main(String[] args) {

       // Bank accounts creation
       BankAccount accounts[] = new BankAccount[] { new BankAccount(200), new BankAccount(1500), new BankAccount(1000),
               new BankAccount(2000), new BankAccount(3000), new BankAccount(0), new BankAccount(50), };

       BalanceMeasurer measurer = new BalanceMeasurer();
      
       // previously we use the BalanceFilter class which implements the filter
       // Now below is the lambda expression which implements for the single method from filter interface
       Filter filter = (object) -> {
           // returns the boolean if the balance is greater than the 1000
           return ((BankAccount) object).getBalance() >= 1000;
       };
            
       // calling the average method with filter
       double avg = average(accounts, measurer, filter);
       System.out.println("Average for bank accounts with 1000.00 in collateral is " + avg);
   }
}

=================================

Filter.java

// Annotate the interface to be functional interface
@FunctionalInterface
public interface Filter {
// this is what sifts through the -1000 and +1000 accounts
   boolean accept(Object anObject);
}

===================================

Measurer.java
public interface Measurer
{   
double measure(Object anObject);
}

===================================

BankAccount.java

public class BankAccount {
   private double balance;

   public BankAccount() {
       balance = 0;
   }

   public BankAccount(double initialBalance) {
       balance = initialBalance;
   }

   public void deposit(double amount) {
       balance = balance + amount;
   }

   public void withdraw(double amount) {
       balance = balance - amount;
   }

   public double getBalance() {
       return balance;
   }

   public void addIntrest(double rate) {
       balance = balance + balance * rate / 100;
   }

}

========================================

BalanceMeasurer.java

public class BalanceMeasurer implements Measurer {
   public double measure(Object object) {
       return ((BankAccount) object).getBalance();
   }

}

========================================

output

========================================


Related Solutions

JAVA CODE --- from the book, java programming (7th edition) chapter 7 carly's question I am...
JAVA CODE --- from the book, java programming (7th edition) chapter 7 carly's question I am getting a illegal expression error and don't know how to fix it, also may be a few other error please help CODE BELOW import java.util.Scanner; public class Event { public static double pricePerGuestHigh = 35.00; public static double pricePerGuestLow = 32.00; public static final int LARGE_EVENT_MAX = 50; public String phnum=""; public String eventNumber=""; private int guests; private double pricePerEvent; public void setPhoneNumber() {...
JAVA 1. Create an Interface Vehicle. Declare one public void method in it paint( ). 2....
JAVA 1. Create an Interface Vehicle. Declare one public void method in it paint( ). 2. Create a class Car. Implements Vehicle. It's paint() method prints "Car Painted". It's drive( ) method prints "Car Driven". 3. Create a class Bus. Implements Vehicle. It's paint() method prints "Bus Painted" . It's drive( ) method prints "Bus Driven".   4. Create a method AutoWork which accepts an object of type Vehicle. The method makes a call to the vehicle's paint( ) and drive()...
Finish the following java question: Consider the following interface: interface Duty { public String getDuty(); }...
Finish the following java question: Consider the following interface: interface Duty { public String getDuty(); } Write a class called Student which implements Duty. Class Student adds 1 data field, id, and 2 methods, getId and setId, along with a 1-argument constructor. The duty of a Student is to study 40 hours a week. Write a class called Professor which implements Duty. Class Professor adds 1 data field, name, and 2 methods, getName and setName, along with a 1-argument constructor....
In regards to Statistics: the exploration and and analysis of data (7th edition), chapter 13, question...
In regards to Statistics: the exploration and and analysis of data (7th edition), chapter 13, question 43. Part a of the question asks for the equation of an estimated regression line. The solution is already on chegg, but my question is: why are SSR, Se, and Sb still calculated, after y-hat=2.7...+(0.04...)x has already been solved for?
java from control structures through objects 6th edition, programming challenge 5 on chapter 16 Write a...
java from control structures through objects 6th edition, programming challenge 5 on chapter 16 Write a boolean method that uses recursion to determine whether a string argument is a palindrome. the method should return true if the argument reads the same forward amd backword. Demonstrate the method in a program, use comments in the code for better understanding. there must be a demo class and method class also .. generate javadocs through eclipse compiler. And make a UML diagram with...
java: Given the definitions: public interface ActionListener { public void actionPerformed(ActionEvent e); } public JTextField {...
java: Given the definitions: public interface ActionListener { public void actionPerformed(ActionEvent e); } public JTextField { public JTextField(){} public void setText(String text) {} public String getText() {} } Write the code to create a JButton on the South of the window and a JTextField on the North. The first time you click on the button, it should print out “hello!” on the JTextField. For the second time, should show “hello!hello!”. For the third time, should show “hello!hello!hello!”.
Registry Java Programming 2) Interface Comparator: The method for comparing two objects is written outside of...
Registry Java Programming 2) Interface Comparator: The method for comparing two objects is written outside of the class of the objects to be sorted. Several methods can be written for comparing the objects according to different criteria. Specifically, write three classes, DescriptionComparator, FirstOccComparator, and LastOccComparator that implement the interface java.util.Comparator. DescriptionComparator implements the interface Comparator. The method compare compares the description of two objects. It returns a negative value if the description of the first object comes before the description...
Using Java The given class SetInterface.java is : public interface SetInterface<T> {    /**    *...
Using Java The given class SetInterface.java is : public interface SetInterface<T> {    /**    * Gets the current number of entries in this set.    *    * @return The integer number of entries currently in the set.    */    public int getSize();    /**    * Sees whether this set is empty.    *    * @return True if the set is empty, or false if not.    */    public boolean isEmpty();    /**    *...
The readings and images come from the book Fiero, Gloria K., The Humanistic Tradition, 7th edition,...
The readings and images come from the book Fiero, Gloria K., The Humanistic Tradition, 7th edition, vol. II. 1) In Discourse on Method (Reading 23.3) how does Rene Descartes prove (at least to his own satisfaction) that the mind and body are separate and distinct from each other? 2) How do Thomas Hobbes and John Locke differ in their views of human nature? Why did each of them believe men create governments? Did you think Adam Smith would agree more...
IN JAVA Step 1 Develop the following interface: Interface Name: ImprovedStackInterface Access Modifier: public Methods Name:...
IN JAVA Step 1 Develop the following interface: Interface Name: ImprovedStackInterface Access Modifier: public Methods Name: push Access modifier: public Parameters: item (data type T, parameterized type) Return type: void Throws: StackFullException Name: push Access modifier: public Parameters: item1 (data type T, parameterized type), item2 (data type T, parameterized type) Return type: void Throws: StackFullException Name: pop Access modifier: public Parameters: none Return type: void Throws: StackEmptyException Name: doublePop Access modifier: public Parameters: none Return type: void Throws: StackEmptyException Name:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT