Skip to content

Instantly share code, notes, and snippets.



Last active Nov 24, 2020
What would you like to do?
Simple utility method to check for 'emptiness' of objects.The 'emptiness' criteria is defined by a java.util.function.Predicate.On the lines of Objects.requireNonNull
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
public class RandomGist {
public static <T> T requireNonEmpty(T object, Predicate<T> predicate, String msgToCaller){
if (predicate.test(object)){
throw new IllegalArgumentException(msgToCaller);
return object;
public static void main(String[] args) {
//Usage 1: an empty string (intentional)
String s = "";
System.out.println(requireNonEmpty(Objects.requireNonNull(s), (s1) -> s1.isEmpty() , "My String is Empty!"));
//Usage 2: an empty List (intentional)
List list = Collections.emptyList();
System.out.println(requireNonEmpty(Objects.requireNonNull(list), (l) -> l.isEmpty(), "List is Empty!").size());
//Usage 3: an empty User (intentional)
User user = new User("");
System.out.println(requireNonEmpty(Objects.requireNonNull(user), (u) -> u.getName().isEmpty(), "User is Empty!"));
private static class User {
private String name;
public User(String name){ = name;
public String getName(){
return name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment