Check ArrayList content with Java stream
Use filters
List<Object> objLst = new ArrayList<Object>(Arrays.asList(new Object[] {new User(), new Person(), new Dummy() }));
return (objLst.stream()
.filter(e -> !(e instanceof User || e instanceof Person))
.limit(1)
.count() > 0) ? null : objLst;
Alternative to Paul's answer (with the if-else in your question)
if (arrayList.stream().allMatch(o -> o instanceof Person || o instanceof User)) {
return null;
} else {
return arrayList;
}
Assuming Person
and User
are types, rather than specific objects, you can do something like this.
return list.stream()
.filter(o -> !(o instanceof Person) && !(o instanceof User))
.findAny()
.isPresent() ? list : null;