我有一個 Book 課程,然后我制作了一個List<Book>. 我在檢查所有屬性時遇到問題。以下是 a 的程式代碼示例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>,然后回傳布爾邏輯回傳訊息例子id 2 has empty value?
uj5u.com熱心網友回復:
您可以使用Apache Commons 中的StringUtils.isEmpty(...)方法,或者如果您不想要依賴項,您可以像這樣撰寫它:
public static boolean isEmpty(String s) {
return s == null || s.isEmpty();
}
要檢查所有authors的List使用流:
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());
uj5u.com熱心網友回復:
要檢查類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()));
輸出:
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
uj5u.com熱心網友回復:
您可以使用反射,這樣您就不需要單獨手動測驗每個檔案:
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);
}
輸出:
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
);
}
uj5u.com熱心網友回復:
或者你可以使用 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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367479.html
