偵測 Null

使用 Java 進行資料清理

Dennis Lee

Software Engineer

資料在哪裡?

  • 遺漏資料:null 與空白
    • Null:資料不存在
    • 空白:僅空白字元,可能是錯誤

 

Title Publish Date Rating Review Count Price
Python Crash Course 1/10/23 4.8 165 $30.61
9/13/19 4.8 2,521 $38.00
Clean Code 8/1/08 [null] [null] [null]
使用 Java 進行資料清理

來自 null 的錯誤

// book is missing reviewCount, rating, and price
BookSales book = new BookSales("Clean Code", LocalDate.of(2008, 8, 1),
                               null, null, null)


// rating is null, so the code will throw a NullPointerException int rating = book.rating();
Exception in thread "main" java.lang.NullPointerException
使用 Java 進行資料清理

檢查 null 值

// Import Objects
import java.util.Objects;
// Use .isNull()
if (Objects.isNull(book.rating())) {
    System.out.println("Missing rating");
}
Missing rating
使用 Java 進行資料清理

為 null 提供預設值

import java.util.Optional;
// Use Optional.ofNullable for numbers
double rating = Optional.ofNullable(book.rating()).orElse(0.0);
System.out.println("Book rating: " + rating);
Book rating: 0.0
// Use Objects.toString for strings
String displayTitle = Objects.toString(book.title(), "[No Title]");
System.out.println(displayTitle);
Book title: [No Title]
使用 Java 進行資料清理

檢查空白/null 字串

import org.apache.commons.lang3.StringUtils;  // Utility for string operations
// book is missing a title
BookSales book = new BookSales(" ", LocalDate.of(2019, 9, 13), 2521, 4.5, 38.00)


if StringUtils.isBlank(book.title()) { System.out.println("Invalid - empty title"); }
Invalid - empty title
使用 Java 進行資料清理

檢查空白數值

// priceText is blank
String priceText = " ";

// Check for blank values before converting to a number
if StringUtils.isBlank(priceText) {
    System.out.println("Invalid price: blank detected");
}
Invalid price: blank detected
使用 Java 進行資料清理

總結:偵測 null 與空白

  • Null 表示遺漏或未定義的資料
    • 重要匯入:java.util.Objectsjava.util.Optional
    • 先檢查 null 再使用,可避免 NullPointerException
    • Objects.isNull() 檢查 null
    • Optional.ofNullable() 提供預設值
  • 空白表示空字串或僅含空白字元
    • 重要匯入:org.apache.commons.lang3.StringUtils
    • StringUtils.isBlank() 偵測 ""、null、或空白字元
    • 常見於資料輸入錯誤
使用 Java 進行資料清理

一起來練習吧!

使用 Java 進行資料清理

Preparing Video For Download...