Xác minh kiểu dữ liệu

Làm sạch dữ liệu bằng Java

Dennis Lee

Software Engineer

Vì sao cần kiểm tra kiểu dữ liệu?

  • Cần phân tích văn bản từ nguồn dữ liệu bên ngoài
  • Kiểu dữ liệu không hợp lệ gây lỗi runtime
  • Xác thực đúng giúp tránh sập chương trình

 

String priceText = "$30.61";
double price = Double.parseDouble(priceText);  // Lỗi: $ không hợp lệ trong số
Exception in thread "main" java.lang.NumberFormatException
Làm sạch dữ liệu bằng Java

Xác thực văn bản số

// Tiện ích kiểm tra số
import org.apache.commons.lang3.math.NumberUtils; 
String reviewCountText = "165";
System.out.println(NumberUtils.isParsable(reviewCountText));
true
String priceText = "$30.61"; // Không phải số hợp lệ
System.out.println(NumberUtils.isParsable(priceText)); // false: có ký hiệu $
false
Làm sạch dữ liệu bằng Java

Phân tích văn bản số

private static String validateNumeric(String value) {
    if (NumberUtils.isParsable(value)) return value;  // Hợp lệ thì trả về
    throw new IllegalArgumentException("Invalid: " + value);  // Ngược lại ném lỗi
}

int reviews = Integer.parseInt(validateNumeric("165"));  // Xác thực rồi parse

// Loại bỏ ký hiệu $ double price = Double.parseDouble(validateNumeric("$30.61".replace("$", ""))); System.out.println("reviews: " + reviews + "\nprice in $: " + price);
reviews: 165
price in $: 30.61
Làm sạch dữ liệu bằng Java

Xác thực định dạng ngày

import java.time.format.DateTimeFormatter; // Định dạng mẫu ngày
private static LocalDate parseDate(String dateStr) {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("M/d/yy");

return LocalDate.parse(dateStr, format); // Chuỗi -> LocalDate }
LocalDate date = parseDate("1/10/23"); // "1/10/23" chuyển thành 2023-01-10 System.out.println("Date: " + date);
Date: 2023-01-10
Làm sạch dữ liệu bằng Java

Kết hợp xác thực số và ngày

private static double parsePrice(String price) {
    return Double.parseDouble(validateNumeric(price.replace("$", "")); // Bỏ ký hiệu $
}


// Chuyển trường CSV thành BookSales public static BookSales parseSalesData(String[] fields) { String title = fields[0]; LocalDate publishDate = parseDate(fields[1]); // Phân tích ngày tùy chỉnh int reviews = Integer.parseInt(validateNumeric(fields[2])); double rating = Double.parseDouble(validateNumeric(fields[3])); double price = parsePrice(fields[4]); // Xử lý định dạng tiền tệ return new BookSales(title, publishDate, reviews, rating, price); }
Làm sạch dữ liệu bằng Java

Đọc tệp CSV an toàn

List<BookSales> sales = new ArrayList<>(); // Lưu các đối tượng BookSales


try (BufferedReader reader = new BufferedReader(new FileReader("book_sales.csv"))) {
String line = reader.readLine(); // Bỏ qua dòng tiêu đề
while ((line = reader.readLine()) != null) { // Đọc đến cuối tệp String[] fields = line.split(","); // Tách dòng CSV thành mảng sales.add(parseSalesData(fields)); // Chuyển thành đối tượng BookSales } }
sales.forEach(System.out::println); // In từng bản ghi
BookSales[title=Python Crash Course, publishDate=2023-01-10, 
reviewCount=165, rating=4.8, price=30.61]
Làm sạch dữ liệu bằng Java

Tóm tắt: xác minh kiểu dữ liệu

  • Xác thực văn bản trước khi phân tích để tránh lỗi runtime
  • Thư viện chính
    • org.apache.commons.lang3.math.NumberUtils
    • java.time.format.DateTimeFormatter
  • Dùng NumberUtils.isParsable() để kiểm tra chuỗi số
  • Xử lý nhiều định dạng ngày với DateTimeFormatter
  • Bắt lỗi kiểu dữ liệu để đảm bảo toàn vẹn dữ liệu
Làm sạch dữ liệu bằng Java

Ayo berlatih!

Làm sạch dữ liệu bằng Java

Preparing Video For Download...