简体   繁体   中英

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".

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 change the name field.
  • In most cases, we should work with List<Item> (interface), and not ArrayList<Item> (implementation).

You can remove from a list all elements who doesn't have "Sam" name by using removeIf method:

itemsNamedSam.removeIf(item -> !item.name.equals("Sam"));

With the help of @Alex's comment, What I ended up doing is:

 public static List<Item> findItemsByName(Collection<Item> listItems, String name) {
        
     return listItems.stream().filter(item -> name.equals(item.getName()))
    .collect(Collectors.toList());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM