資料轉換模式

Java 中的資料匯入

Anthony Markham

VP Quant Developer

Map 函式

  • 對欄位中的每個元素進行轉換
DoubleColumn celsius = DoubleColumn.create("Celsius", 0, 10, 20, 30);

DoubleColumn fahrenheit = celsius.map(c -> c * 9.0/5.0 + 32); table.addColumns(fahrenheit.setName("Fahrenheit"));
Celsius Fahrenheit
0.0 32.0
10.0 50.0
20.0 68.0
30.0 86.0
Java 中的資料匯入

Reduce 函式

  • 將欄位所有值彙整為單一結果
  • 套用累加器模式(如 sum、max,或自訂邏輯)
  • 適用統計與分析作業
// Find the total sales
double totalSales = table.doubleColumn("Sales").reduce(0, Double::sum);
250000
// Find the maximum
double largeSales = table.doubleColumn("Sales").reduce(0, (acc, x) -> acc + (x > 5000 ? 1 : 0));
68
Java 中的資料匯入

使用 forEach 的逐列迭代

  • 逐列走訪整個資料表
DoubleColumn difference = DoubleColumn.create("Difference");
table.forEach(row -> {
    double celsius = row.getDouble("Celsius");
    double fahrenheit = row.getDouble("Fahrenheit");
    difference.append(fahrenheit - celsius);
});

table.addColumns(difference);
Celsius Fahrenheit Difference
0.0 32.0 32.0
10.0 50.0 40.0
20.0 68.0 48.0
Java 中的資料匯入

轉換流程(pipeline)

  • 串接多個操作
  • 提升程式碼可讀性與可維護性 ✅
  • 高效處理資料 ✅
Table result = originalTable
    .where(numberColumn("Age").isGreaterThan(18)) // Filter on Age > 18

.addColumns( numberColumn("Income").map(i -> i * 1.1).setName("AdjustedIncome") );
// Calculate average income double avgIncome = result.doubleColumn("AdjustedIncome") .reduce(0.0, Double::sum) / result.rowCount();
Java 中的資料匯入

重點回顧

  • map()-將函式套用於欄位值以進行轉換
  • forEach()-逐列迭代以存取多個欄位
  • reduce()-彙總並將資料摘要為單一值

顯示三種資料轉換函式的圖片

Java 中的資料匯入

一起來練習吧!

Java 中的資料匯入

Preparing Video For Download...