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


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

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;

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

  public Candy() {

  public Candy(String name, float price, boolean InStock) {

  public String getName() {
    return name;

  public void setName(String 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;


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:


The equivalent non-stream version would be:

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

Leave a Reply

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