How to return specific attributes from a stream method

I made a method in my item class which filters through my Array list items which has less than 2 quantities.

The method is returning all the attributes of that item when I want only its name and price.

I’m stuck on what needs to be change in my method

public static List<item>  findquantity(List<item> items) { 
    return items.stream()
      .filter(item -> item.getquantity()< 2)
      .collect(Collectors.toList());
}

I am calling the method in my main as

System.out.println(item.findquantity(itemDatabase));

Answer

If you change the return type of findQuantity to Map<String, Double> instead of List<Item>, you can use Collectors.toMap() to return only name and price :

public static Map<String, Double>  findQuantity(List<Item> items) { 
    return items.stream().filter(item -> item.getQuantity() < 2)
            .collect(Collectors.toMap(Item::getName, Item::getPrice));
}

A better way is to create a custom object that holds the values as referred in the comments by @Thomas. Should be something like this:

items.stream().filter(item -> item.getQuantity() < 2).map(i -> new CustomItem(i.getName(), i.getPrice()))
                .collect(Collectors.toList());

Leave a Reply

Your email address will not be published. Required fields are marked *