Search code examples
javaarraylistcollections

How to get a list of objects with same objects property from an ArrayList by


How to retrieve a list of all the objects in an ArrayList with object property.

Model Class:

public class Item {
  private String id;
  private String name;
}

ArrayList<Item> items = new ArrayList();

Now, how can we search ArrayList with a particular name?

Eg: Get all the objects that have the name "Sam".


Solution

  • You can do:

    List<Item> itemsNamedSam = items.stream()
        .filter(item -> item.name.equals("Sam"))
        .collect(Collectors.toList())
    

    Few notes:

    • You should probably make the fields in Item- private. For example, as things stand you might accidentally reassign the name field.
    • In most cases, we should work with List<Item> (interface), and not ArrayList<Item> (implementation).