How to check if list is empty in Java 8 using Optional
Categories: Java 8(JDK1.8) Java Java Examples
package r4r.co.in;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class CheckListIsEmptyOrNot {
public static void main(String[] args) {
//How to check if list is empty in Java 8 using Optional
//if not null iterate through the list and print the object
List<String> checkList=null;//Arrays.asList("Rajesh");
List<String> list= Arrays.asList("Rajesh","Kumar");
Optional.ofNullable(checkList).orElse(list).stream().filter(Objects::nonNull).forEach(System.out::println);
}
}
OutPut:-
Rajesh
Kumar