Refactor ExcelPOIHelper to Stream API

This commit is contained in:
pivovarit 2017-02-18 08:31:42 +01:00
parent f800e9dc4f
commit 2bf21cbff3
1 changed files with 14 additions and 17 deletions

View File

@ -24,6 +24,7 @@ import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.IntStream;
public class ExcelPOIHelper { public class ExcelPOIHelper {
@ -38,27 +39,23 @@ public class ExcelPOIHelper {
data = readXSSFWorkbook(fis); data = readXSSFWorkbook(fis);
} }
int maxNrCols = 0; int maxNrCols = data.values().stream()
.mapToInt(List::size)
.max()
.orElse(0);
for (List<MyCell> ls : data.values()) { data.values().stream()
if (ls.size() > maxNrCols) { .filter(ls -> ls.size() < maxNrCols)
maxNrCols = ls.size(); .forEach(ls -> {
} IntStream.range(ls.size(), maxNrCols)
} .forEach(i -> ls.add(new MyCell("")));
});
for (List<MyCell> ls : data.values()) {
if (ls.size() < maxNrCols) {
for (int i = ls.size(); i < maxNrCols; i++) {
ls.add(new MyCell(""));
}
}
}
return data; return data;
} }
private String readCellContent(Cell cell) { private String readCellContent(Cell cell) {
String content = ""; String content;
switch (cell.getCellTypeEnum()) { switch (cell.getCellTypeEnum()) {
case STRING: case STRING:
content = cell.getStringCellValue(); content = cell.getStringCellValue();
@ -91,7 +88,7 @@ public class ExcelPOIHelper {
HSSFSheet sheet = workbook.getSheetAt(0); HSSFSheet sheet = workbook.getSheetAt(0);
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i); HSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<MyCell>()); data.put(i, new ArrayList<>());
if (row != null) { if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) { for (int j = 0; j < row.getLastCellNum(); j++) {
HSSFCell cell = row.getCell(j); HSSFCell cell = row.getCell(j);
@ -144,7 +141,7 @@ public class ExcelPOIHelper {
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i); XSSFRow row = sheet.getRow(i);
data.put(i, new ArrayList<MyCell>()); data.put(i, new ArrayList<>());
if (row != null) { if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) { for (int j = 0; j < row.getLastCellNum(); j++) {
XSSFCell cell = row.getCell(j); XSSFCell cell = row.getCell(j);