Skip to content

Instantly share code, notes, and snippets.

@abhirockzz
Last active November 24, 2020 14:13
Show Gist options
  • Save abhirockzz/6b7d463e2575c3d635e4 to your computer and use it in GitHub Desktop.
Save abhirockzz/6b7d463e2575c3d635e4 to your computer and use it in GitHub Desktop.
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){
Objects.requireNonNull(object);
Objects.requireNonNull(predicate);
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){
this.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