0% found this document useful (0 votes)
35 views4 pages

Assignment 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views4 pages

Assignment 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

ASSIGNMENT – 4

PROGRAM

import java.util.*;

import java.util.stream.Collectors;

class Product {

private String name;

private String category;

private double price;

public Product(String name, String category, double price) {

this.name = name;

this.category = category;

this.price = price;

public String getName() {

return name;

public String getCategory() {

return category;
}

public double getPrice() {

return price;

@Override

public String toString() {

return "Product{name='" + name + "', category='" + category + "', price=" + price + "}";

public class ProductStreamOperations {

public static void main(String[] args) {

List<Product> products = Arrays.asList(

new Product("Laptop", "Electronics", 1500),

new Product("Smartphone", "Electronics", 800),

new Product("Refrigerator", "Home Appliances", 1200),

new Product("TV", "Electronics", 900),

new Product("Blender", "Home Appliances", 150),

new Product("Oven", "Home Appliances", 300)

);

// Find all products that have a price greater than 1000

List<Product> expensiveProducts = products.stream()


.filter(p -> p.getPrice() > 1000)

.collect(Collectors.toList());

System.out.println("Products with price greater than 1000: " + expensiveProducts);

// Calculate the total price of all products in the list

double totalPrice = products.stream()

.mapToDouble(Product::getPrice)

.sum();

System.out.println("Total price of all products: " + totalPrice);

// Find the product with the highest price

Product highestPricedProduct = products.stream()

.max(Comparator.comparingDouble(Product::getPrice))

.orElseThrow(NoSuchElementException::new);

System.out.println("Product with the highest price: " + highestPricedProduct);

// Create a list of product names sorted alphabetically

List<String> sortedProductNames = products.stream()

.map(Product::getName)

.sorted()

.collect(Collectors.toList());

System.out.println("Product names sorted alphabetically: " + sortedProductNames);

// Count the number of products in each category

Map<String, Long> productCountByCategory = products.stream()


.collect(Collectors.groupingBy(Product::getCategory, Collectors.counting()));

System.out.println("Number of products in each category: " + productCountByCategory);

You might also like