Skip to content

Commit 2bf21cb

Browse files
committed
Refactor ExcelPOIHelper to Stream API
1 parent f800e9d commit 2bf21cb

1 file changed

Lines changed: 14 additions & 17 deletions

File tree

‎spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java‎

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import java.util.HashMap;
2525
import java.util.ArrayList;
2626
import java.util.List;
27+
import java.util.stream.IntStream;
2728

2829
public class ExcelPOIHelper {
2930

@@ -38,27 +39,23 @@ public Map<Integer, List<MyCell>> readExcel(String fileLocation) throws IOExcept
3839
data = readXSSFWorkbook(fis);
3940
}
4041

41-
int maxNrCols = 0;
42+
int maxNrCols = data.values().stream()
43+
.mapToInt(List::size)
44+
.max()
45+
.orElse(0);
4246

43-
for (List<MyCell> ls : data.values()) {
44-
if (ls.size() > maxNrCols) {
45-
maxNrCols = ls.size();
46-
}
47-
}
48-
49-
for (List<MyCell> ls : data.values()) {
50-
if (ls.size() < maxNrCols) {
51-
for (int i = ls.size(); i < maxNrCols; i++) {
52-
ls.add(new MyCell(""));
53-
}
54-
}
55-
}
47+
data.values().stream()
48+
.filter(ls -> ls.size() < maxNrCols)
49+
.forEach(ls -> {
50+
IntStream.range(ls.size(), maxNrCols)
51+
.forEach(i -> ls.add(new MyCell("")));
52+
});
5653

5754
return data;
5855
}
5956

6057
private String readCellContent(Cell cell) {
61-
String content = "";
58+
String content;
6259
switch (cell.getCellTypeEnum()) {
6360
case STRING:
6461
content = cell.getStringCellValue();
@@ -91,7 +88,7 @@ private Map<Integer, List<MyCell>> readHSSFWorkbook(FileInputStream fis) throws
9188
HSSFSheet sheet = workbook.getSheetAt(0);
9289
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
9390
HSSFRow row = sheet.getRow(i);
94-
data.put(i, new ArrayList<MyCell>());
91+
data.put(i, new ArrayList<>());
9592
if (row != null) {
9693
for (int j = 0; j < row.getLastCellNum(); j++) {
9794
HSSFCell cell = row.getCell(j);
@@ -144,7 +141,7 @@ private Map<Integer, List<MyCell>> readXSSFWorkbook(FileInputStream fis) throws
144141

145142
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
146143
XSSFRow row = sheet.getRow(i);
147-
data.put(i, new ArrayList<MyCell>());
144+
data.put(i, new ArrayList<>());
148145
if (row != null) {
149146
for (int j = 0; j < row.getLastCellNum(); j++) {
150147
XSSFCell cell = row.getCell(j);

0 commit comments

Comments
 (0)