You can use reflection so that you do not need to manually test each filed separately:
static void testAllFieldsForNull(List<Book> bookList) throws IllegalAccessException {
for (int i = 0; i < bookList.size(); i++){
Book book = bookList.get(i);
Field[] fields = book.getClass().getDeclaredFields();
for(Field field: fields){
Class<?> fieldType = field.getType();
if(!fieldType.isPrimitive()){
if (field.get(book) == null){
System.out.println("Field [" + field.getName() + "] has null value for book at position " + i);
continue;
}
if(fieldType.isAssignableFrom(String.class) && ((String)field.get(book)).isEmpty()){
System.out.println("Field [" + field.getName() + "] is empty String for book at position " + i);
}
}
}
}
}
Test:
public static void main(String[] args) throws IllegalAccessException {
Book b = new Book(1, "", "Ok");
Book c = new Book(2, "Z", "");
Book d = new Book(0, "C", null);
List<Book> x = new ArrayList<>();
x.add(b);
x.add(c);
x.add(d);
testAllFieldsForNull(x);
}
Output:
Field [name] is empty String for book at position 0
Field [author] is empty String for book at position 1
Field [author] has null value for book at position 2
OR if you need to just collect "good" books (actually any sort of oject) you can use:
public static boolean testObject(Object obj){
Field[] fields = obj.getClass().getDeclaredFields();
boolean okay = true;
for(Field field: fields){
Class<?> fieldType = field.getType();
try{
if(!fieldType.isPrimitive()){
if (field.get(obj) == null){
okay = false;
continue;
}
if(fieldType.isAssignableFrom(String.class) && ((String)field.get(obj)).isEmpty()){
okay = false;
}
}
}catch (IllegalAccessException e){
e.printStackTrace();
return false;
}
}
return okay;
}
and then use that for filtering:
public static void main(String[] args) throws IllegalAccessException {
Book b = new Book(1, "", "Ok");
Book c = new Book(2, "Z", "");
Book d = new Book(0, "C", null);
Book a = new Book(3, "C", "D");
List<Book> x = new ArrayList<>();
x.add(b);
x.add(c);
x.add(d);
x.add(a);
System.out.println(
x
.stream()
.filter(FieldTest::testObject)
.collect(Collectors.toList()).get(0).id
);
}