Question: You are tasked to write a Java program that filters a list of products using Predicate and negate ( ) methods. The program should receive

You are tasked to write a Java program that filters a list of products using Predicate and negate() methods. The program should receive a list of products and two predicates. The first predicate should filter out products that are out of stock, and the second predicate should filter out products that have a price greater than $500. Your program should return a list of products that match both predicates.
Instructions:
Create a Product class with the following attributes: name (String), price (double), and isOutOfStock (boolean).
Define a List of Product objects with at least 5 elements.
Define a Predicate that returns true if the given product is out of stock.
Define a Predicate that returns true if the given product's price is greater than $500.
Use the Predicate and negate() methods to filter the list of products. First, filter out products that are out of stock, and then filter out products that have a price greater than $500.
Print the resulting list of products.
Suggested Skeleton:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
class Product {
private String name;
private double price;
private boolean isOutOfStock;
// Constructor, getters, and setters
@Override
public String toString(){
return "Product{"+
"name='"+ name +'\''+
", price="+ price +
", isOutOfStock="+ isOutOfStock +
'}';
}
}
public class PredicateExample {
public static void main(String[] args){
List products = new ArrayList<>(Arrays.asList(
new Product("iPhone 12",999.99, false),
new Product("MacBook Pro", 1499.99, false),
new Product("iPad Pro", 799.99, true),
new Product("AirPods",159.99, false),
new Product("Apple Watch", 349.99, true)
));
//Write your first predicate code here
//Write your second predicate code here
// Research stream().filter(...) and write the code for filtering here
//Write the code to print the filtered list code here
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!