首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java List 轉換:提取鍵值對重構為指定結構列表

     編輯:程式設計疑難解答

需求場景

原始 Map:{/dev/vg00/lvol7=/dev/vg00, /dev/vg00/lvol6=/dev/vg00, ...},每個 Key 唯一。需轉換為 List<Map>,每個元素包含固定鍵 one、two、three,值分別為原 Key、原 Value、固定 IP。

實現代碼

import java.util.*;

public class MapTransform {
    public static void main(String[] args) {
        // 模擬原始數據
        Map sourceMap = new HashMap<>();
        sourceMap.put("/dev/vg00/lvol7", "/dev/vg00");
        sourceMap.put("/dev/vg00/lvol6", "/dev/vg00");
        sourceMap.put("/dev/vg00/lvol5", "/dev/vg00");
        // ... 更多數據
        
        // 目標列表
        List> targetList = new ArrayList<>();
        String fixedIp = "192.168.1.100"; // 固定 three 字段值
        
        // 遍歷轉換
        for (Map.Entry entry : sourceMap.entrySet()) {
            Map item = new HashMap<>();
            item.put("one", entry.getKey());
            item.put("two", entry.getValue());
            item.put("three", fixedIp);
            targetList.add(item);
        }
        
        // 輸出驗證
        for (Map m : targetList) {
            System.out.println(m);
        }
        // 輸出示例: {one=/dev/vg00/lvol7, two=/dev/vg00, three=192.168.1.100}
    }
}

進階:使用 Stream API (Java 8+)

List> targetList = sourceMap.entrySet().stream()
    .map(entry -> {
        Map m = new HashMap<>();
        m.put("one", entry.getKey());
        m.put("two", entry.getValue());
        m.put("three", "192.168.1.100");
        return m;
    })
    .collect(Collectors.toList());

數據庫存儲建議

若需持久化到數據庫,有兩種主流方案:

方案一:關係表(推薦結構化查詢)

CREATE TABLE device_volume (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    volume_path VARCHAR(255) NOT NULL,  -- one
    vg_name VARCHAR(255) NOT NULL,      -- two
    server_ip VARCHAR(45) NOT NULL,     -- three
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

批量插入:

String sql = "INSERT INTO device_volume (volume_path, vg_name, server_ip) VALUES (?, ?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    for (Map item : targetList) {
        ps.setString(1, item.get("one"));
        ps.setString(2, item.get("two"));
        ps.setString(3, item.get("three"));
        ps.addBatch();
    }
    ps.executeBatch();
}

方案二:JSON 字段(適合結構變動頻繁)

CREATE TABLE device_snapshot (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    data JSON NOT NULL,  -- 存儲整個 List 的 JSON 序列化
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

總結

核心邏輯是 遍歷 entrySet → 構建新 Map → 加入 List。Java 8 Stream 寫法更簡潔。持久化時優先考慮關係表便於索引查詢,JSON 適用於非結構化或頻繁變更的場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved