0

`/I am checking this code to filter among collections data using stream api. I supposed to get list of two products which satisfy my condition But I am getting output in decrypted format./

package streamsapi;

import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors;

public class StreamFilter {

public static void main(String[] args) {
    
    // TODO Auto-generated method stub
    /*
     * List<product>list = new ArrayList<product>(); for (product product :
     * getProducts()) { if(product.getPrice()>2500f) { list.add(product); }
     * 
     * } for (product product : list) { System.out.println(product); }
     */
    
    
      List<product>list2 = getProducts().stream() .filter((product)->
      product.getPrice() > 2500f) .collect(Collectors.toList());
      list2.forEach(System.out::println);
     
}
private static List<product> getProducts(){
List<product>ProductsList = new ArrayList<product>();
ProductsList.add(new product(1,"hp",2500f));
ProductsList.add(new product(2,"Dell",3500f));
ProductsList.add(new product(3,"Asus",4500f));
return ProductsList;

}}
class product{
    private int id;
    private String name;
    private float price;
    public product(int id, String name, float price) {
        super();
        this.name = name;
        this.id = id;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    
}

/*and My output is

streamsapi.product@3feba861 streamsapi.product@5b480cf9 */`

jeev
  • 1
  • 1

1 Answers1

0

I think you just need to override the toString in the Product class so that the System.out::println can print the object content not the reference

class product{
    ...

    @Override
    public String toString() {
      return "Product{" +
          "id=" + id +
          ", name=" + name +
          ", price='" + price + '\'' +
          '}';
    }
}
Islam Elbanna
  • 1,438
  • 2
  • 9
  • 15