Using Contains for objects in List collection

I’m trying to find an object in the List collection by his name using Contains method, but, somehow, it doesn’t work. How should I use it?

This is how I try to use this

CandyDao.getAllCandys().contains("Caramel")

But it can’t find an object which I need.

CandyDao.java

public class CandyDao {
  private List<Candy> candys = Arrays.asList(new Candy("Caramel", 3, false),
          new Candy("Marmelade", 2, true));

  public List<Candy> getAllCandys(){
    return candys;
  }
}

Candy.java

  public class Candy {
  private String name;
  private float price;
  private boolean InStock;

  public Candy() {
  }

  public Candy(String name, float price, boolean InStock) {
    setName(name);
    setPrice(price);
    setInStock(InStock);
  }

  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 boolean getInStock() {
    return InStock;
  }

  public void setInStock(boolean InStock) {
    this.InStock = InStock;
  }
}

Answer

Since the list contains Candy objects, the contains() method needs a Candy object for the comparison, so you can’t use contains("Caramel").

To check if the list contains a Candy object with a name of "Caramel", you can use Java 8+ Streams to do the search:

CandyDao.getAllCandys().stream().Map(Candy::getName).anyMatch("Caramel"::equals);

The equivalent non-stream version would be:

boolean hasCaramel = false;
for (Candy candy : CandyDao.getAllCandys()) {
    if ("Caramel".equals(candy.getName())) {
        hasCaramel = true;
        break;
    }
}

Leave a Reply

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