March 3, 2024

Get Range of Items Using Java Stream API

In this post we’ll see how to get range of items from any collection using Java Stream API.

For example I have a list of Products and I want another list of products as per following criteria-

1- List of products that fall with in a passed price range.

Product class
public class Product {
  private String productName;
  private double price;
  Product(String productName, double price){
    this.productName = productName;
    this.price = price;
  }
  public String getProductName() {
    return productName;
  }
  public void setProductName(String productName) {
    this.productName = productName;
  }
  public double getPrice() {
    return price;
  }
  public void setPrice(double price) {
    this.price = price;
  }
  @Override
  public String toString() {
    return getProductName() + " " + getPrice();
  }
}

Here the problem statement is to write a method that is passed minimum price and maximum price as arguments and it should return a list of products that fall with in that price range and this logic should be written using Java Stream API. In the given code, range is passed as minimum price = 10000 and maximum price = 50000

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class StreamRange {

  public static void main(String[] args) {
    StreamRange obj = new StreamRange();
    // Get a list of products
    List<Product> productList = obj.createList();
    obj.productsInPriceRange(productList, 10000, 50000);
  }
  // create list of Products
  private List<Product> createList(){
    List<Product> productList = Arrays.asList(new Product("Screw Driver", 250), 
                                    new Product("Trousers", 3000), 
                                    new Product("RAM", 16000), 
                                    new Product("Smart Watch", 8000),
                                    new Product("Laptop", 48000));
      
    return productList;
  }

  void productsInPriceRange(List<Product> productList, double fromPrice, double toPrice) {
    // sorting is done here so that result comes in price order, not actually needed for the logic
    List<Product> newList = productList.stream()
                                       .sorted(Comparator.comparing(Product::getPrice))
                                       .filter(p -> (p.getPrice() >= fromPrice && p.getPrice() <= toPrice))
                                       .collect(Collectors.toList());
    System.out.println(newList);
  }   
}
Output
[RAM 16000.0, Laptop 48000.0]

2. From the list of Products you want the top 3 priced products using Java Stream API.

void topNPricedProducts(List<Product> productList, int range) {
  // sorting is done in descending order here
  List<Product> newList = productList.stream()
                                     .sorted(Comparator.comparing(Product::getPrice).reversed())
                                     .limit(range)
                                     .collect(Collectors.toList());
  System.out.println(newList);
}

3. From the list of Products you want the bottom 3 priced products. That can be done in following way by chaining sorted() and limit() methods of Java Stream API.

void bottomNPricedProducts(List<Product> productList, int range) {
  // ascending order sorting
  List<Product> newList = productList.stream()
                                     .sorted(Comparator.comparing(Product::getPrice))
                                     .limit(range)
                                     .collect(Collectors.toList());
  System.out.println(newList);
}

4. From the list you want a sub-list of products as per given from and to arguments.

void productSubList(List<Product> productList, int from, int to) {
  List<Product> newList = productList.stream()
                                     .skip(from)
                                     .limit(to)
                                     .collect(Collectors.toList());
  System.out.println(newList);
}

Read more about skip() method here- Java Stream skip() Method With Examples

Read more about limit() method here- Java Stream limit() Method With Examples

That's all for the topic Get Range of Items Using Java Stream API. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment