Filter and sort with a stream
A method filters a list of Item
objects based on a maximum price and then sorts the filtered items by price. Here's a summary of what the method does:
- Filter: It filters the items where the price is less than
maxPrice
. - Sort: It sorts the filtered items by their price in ascending order.
- Collect: It collects the sorted items into a list.
Here is the code with comments and a main
method added for testing:
import java.util.List;
import java.util.stream.Collectors;
class Answer {
// Change these boolean values to control whether you see
// the expected answer and/or hints.
static boolean showExpectedResult = true;
static boolean showHints = false;
// Filter and sort the items array.
static List<Item> getFilteredData(List<Item> items, float maxPrice) {
return items.stream()
.filter(item -> item.getPrice() < maxPrice) // Filter items by price
.sorted((a, b) -> Float.compare(a.getPrice(), b.getPrice())) // Sort items by price
.collect(Collectors.toList()); // Collect results into a list
}
// A model class holding each item's values
public static class Item {
private int id;
private String name;
private float price;
private int quantity;
public Item(int id, String name, float price, int quantity) {
this.id = id;
this.name = name;
this.price = price;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "[" + this.id + ", " + this.name + ", " + this.price + ", " + this.quantity + "]";
}
}
// Main method to test the getFilteredData method
public static void main(String[] args) {
List<Item> items = List.of(
new Item(1, "Item1", 10.0f, 2),
new Item(2, "Item2", 5.0f, 4),
new Item(3, "Item3", 20.0f, 1),
new Item(4, "Item4", 15.0f, 3)
);
float maxPrice = 15.0f;
List<Item> filteredItems = getFilteredData(items, maxPrice);
System.out.println("Filtered and Sorted Items:");
filteredItems.forEach(System.out::println);
}
}
Explanation
Filtering:.filter(item -> item.getPrice() < maxPrice) Filters the items to include only those with a price less than
maxPrice
.Sorting: .sorted((a, b) -> Float.compare(a.getPrice(), b.getPrice())) Sorts the items by their price in ascending order using
Float.compare
for correct floating-point comparison.- Collecting: .collect(Collectors.toList()). Collects the filtered and sorted items into a list.
Comments
Post a Comment