Home > OS >  Find all objects in list that contain a certain field
Find all objects in list that contain a certain field

Time:03-09

I'm trying to find all the objects in a list of objects that contain a particular field name. For example

"list": [
  {
    "namesArray": [],
    "name": "Bob",
    "id": "12345",
  },
  {
    "namesArray": [
      "Jenny"
    ],
    "name": "Ned",
  },
  {
    "namesArray": [],
    "name": "Jane",
    "id": "gkggglg",
  }
 ]

The class looks like this:

class ListItem {
    String id;
    String name;
    List<String> namesArray; 
}

So basically I need to find all the objects that contain the field "id". Something like:

list.stream().filter(li -> li.equals("id")).collect(Collectors.toList());

I've tried following this page and it isn't quite what I want. I don't care about the values of the id's, just whether or not the object has the field at all.

CodePudding user response:

From the comments, we get your actual requirement:

So all objects with a non-null id field.

It's easy to adapt the code you've already got using streams and a filter - you just need to change the predicate that's being passed to the filter method. That predicate needs to return true for any value you want to be in the result, and false for any value you want to be discarded. So all you need is:

var result = list
    .stream()
    .filter(item -> item.id != null)
    .collect(Collectors.toList());
  •  Tags:  
  • java
  • Related