简体   繁体   中英

How to set values to pojo class from Java Hashmap

I have created a below code which will read excel sheet and store the data into hashmap.

   public static void getValue()
    {
      Map<Integer, List<String>> getValues= new HashMap<Integer,List<String>>();
      String fileLocation = ".//clone1//Sample.xls";
      File f = new File(fileLocation);
      FileInputStream fis = new FileInputStream(f);
      Workbook book = new XSSFWorkbook(fis);
      Sheet sheet = book.getSheetAt(0);

        for (int i = 1; i <= sheet.getLastRowNum(); i++) 
        {
                Row row = sheet.getRow(i);
                List<String> datai = new ArrayList<String>();
        for (int j = 0; j < row.getLastCellNum(); j++) 
              {
                row.getCell(j, Row.CREATE_NULL_AS_BLANK);

                datai.add(row.getCell(j).getStringCellValue());
              }
                    getValues.put(i,datai);

        }
    }

OUTPUT of the HashMap some think like below:

Key :0 Values:["mercury","Mercury"]

Key:1 Values:["Amazon","Kindle"]

And "key" represent rows count in excel sheet and "Values" represent the username, and password columns which is stored in List in Map.

As per output the excel sheet has two active rows, and 4 active cell values.

+Sample POJO Class+

   public class DataSet
    {
     private username;
     private password;

     //getter and setters methods for username, and password
    }

I would like to apply the values to pojo class. and which is the efficient way to achieve set the pojo object values from Map.

You can convert it using stream in one sort:

List<DataSet> data = getValues.values().stream()
                .filter(l -> l.getSize() >= 2)
                .map(l -> new DataSet(l.get(0), l.get(1)))
                .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM