You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Java HashMap为POJO类赋值及高效实现方案

Hey there! Let's break down the most efficient ways to map your Excel data to the DataSet POJO. First, let's fix a small issue with your POJO class—you forgot the field types, which will cause compilation errors. Here's the corrected version:

public class DataSet {
    private String username;
    private String password;

    // Getters and Setters
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

1. Most Efficient Approach: Generate POJOs Directly While Reading Excel

The best way to optimize this is to skip the HashMap entirely and create DataSet objects as you read each row of the Excel file. This eliminates the overhead of storing data in an intermediate collection and avoids a separate conversion step, saving both memory and processing time.

Here's the revised code that reads Excel and directly builds a list of DataSet instances:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelReader {
    public static List<DataSet> getDataSetList() {
        List<DataSet> dataSetList = new ArrayList<>();
        String fileLocation = ".//clone1//Sample.xls";
        
        try (FileInputStream fis = new FileInputStream(new File(fileLocation));
             Workbook book = new XSSFWorkbook(fis)) {
            
            Sheet sheet = book.getSheetAt(0);
            // Start from row 1 (assuming row 0 is header)
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue; // Skip empty rows
                
                DataSet dataSet = new DataSet();
                // Handle username (column 0)
                Cell usernameCell = row.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                dataSet.setUsername(getCellStringValue(usernameCell));
                
                // Handle password (column 1)
                Cell passwordCell = row.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                dataSet.setPassword(getCellStringValue(passwordCell));
                
                dataSetList.add(dataSet);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSetList;
    }

    // Helper method to safely get cell value as String, regardless of cell type
    private static String getCellStringValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}

Key Optimizations Here:

  • Uses try-with-resources to auto-close streams/workbook (prevents resource leaks)
  • Skips the HashMap entirely, building POJOs directly
  • Adds a helper method to handle different Excel cell types (avoids getStringCellValue() crashes for non-string cells)
  • Skips empty rows to avoid invalid POJOs

2. Convert Existing HashMap to List

If you already have the existing HashMap<Integer, List<String>> and need to convert it to DataSet objects, use Java 8+ Stream API for a clean, efficient conversion. This is more concise than a traditional loop and performs just as well.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class HashMapConverter {
    public static List<DataSet> convertHashMapToDataSet(Map<Integer, List<String>> hashMap) {
        return hashMap.values().stream()
                .filter(list -> list.size() >= 2) // Ensure we have at least username and password
                .map(list -> {
                    DataSet dataSet = new DataSet();
                    dataSet.setUsername(list.get(0));
                    dataSet.setPassword(list.get(1));
                    return dataSet;
                })
                .collect(Collectors.toList());
    }
}

Notes:

  • The filter step ensures we don't try to access indices that don't exist (prevents IndexOutOfBoundsException)
  • If your Excel has more columns, you can extend this to set additional fields in the POJO

内容的提问来源于stack exchange,提问作者ArrchanaMohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:13:10