[英]How to check list object has null value or empty string?
我有一本書 class 然后我制作了一個List<Book>
。 我在檢查所有屬性時遇到問題。 以下是class Book
的程序代碼示例:
class Book {
int id;
String name,author;
public Book(int id, String name, String author) {
this.id = id;
this.name = name;
this.author = author;
}
}
這是List<Book>
上的代碼片段:
Book b = new Book(1, "", "Ok");
Book c = new Book(2, "Z", "");
Book d = new Book(0, "C", "Ok");
List<Book> x = new ArrayList<>();
x.add(b);
x.add(c);
x.add(d);
如何檢查List<Book>
中的值是否為空字符串或null然后返回 Boolean 並返回消息示例id 2 has empty value
?
您可以使用Apache Commons中的StringUtils.isEmpty(...)
方法,或者如果您不想要依賴項,您可以像這樣編寫它:
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
要檢查List
中的所有authors
,請使用 Streams:
public boolean anyAuthorEmpty(List<Book> books) {
return books.stream().anyMatch(b -> isEmpty(b.getAuthor());
}
要找到確切的Book
,您可以像這樣使用.findFirst()
:
public Book findBookWithEmptyAuthor(List<Book> books) {
return books.stream().filter(b -> isEmpty(b.getAuthor())
.findFirst().orElse(null);
}
如果沒有找到,這將返回Book
或null
。
如果您需要沒有作者的所有內容,您可以使用Collectors.toList()
:
public List<Book> findBooksWithNoAuthor(List<Book> books) {
return books.stream().filter(b -> isEmpty(b.getAuthor())
.collect(Collectors.toList());
您可以使用反射,這樣您就不需要單獨手動測試每個文件:
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);
}
}
}
}
}
測試:
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
或者,如果您只需要收集“好”書籍(實際上是任何類型的物品),您可以使用:
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;
}
然后使用它進行過濾:
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
);
}
要檢查 class Book
的多個屬性,可以提供以下解決方案(假設有輔助方法isNullOrEmpty
的實現):
class SONullEmpty {
static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}
static List<Book> booksWithNullOrEmpty(List<Book> books) {
return books
.stream()
.filter(book -> Stream.of(
book.getName(), book.getAuthor()
).anyMatch(SONullEmpty::isNullOrEmpty)
)
.collect(Collectors.toList());
}
}
類似地,可以實現一個接受Book
屬性的多個 getter 的方法,然后調用:
// in the same SONullEmpty class
static List<Book> withNullOrEmptyAttribs(List<Book> books, Function<Book, String> ... getters) {
return books
.stream()
.filter(book -> Arrays.stream(getters).anyMatch(g -> isNullOrEmpty(g.apply(book))))
.collect(Collectors.toList());
}
測試:
Book b = new Book(1, "", "Ok");
Book c = new Book(2, "Z", "");
Book d = new Book(3, null, "Ok");
List<Book> x = Arrays.asList(b, c, d);
withNullOrEmptyAttribs(x, Book::getName)
.forEach(book -> System.out.printf("Book with id=%d has null or empty name%n", book.getId()));
withNullOrEmptyAttribs(x, Book::getAuthor)
.forEach(book -> System.out.printf("Book with id=%d has null or empty author%n", book.getId()));
Output:
Book with id=1 has null or empty name
Book with id=3 has null or empty name
Book with id=2 has null or empty author
或者你可以使用 Java Stream 也許
public class Test1 {
private Test1()
{
Book b = new Book(1, "", "Ok");
Book c = new Book(2, "Z", "");
Book d = new Book(3, "C", "Ok");
List<Book> x = new ArrayList<>();
x.add(b);
x.add(c);
x.add(d);
boolean empty = x.stream()
.filter(book -> book.name == null || book.name.isEmpty() || book.author == null || book.author.isEmpty())
.count() > 0;
}
class Book
{
int id;
String name, author;
public Book(int id, String name, String author)
{
this.id = id;
this.name = name;
this.author = author;
}
}
public static void main(String[] args)
{
new Test1();
}
}
所以如果你需要檢查字符串是 null 還是空的,你可以 go
//代碼
String s = "somestring" if(s == "" || s == null){ //true }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.