Sebastian Zeki Sebastian Zeki - 6 months ago 13
Java Question

How to ads string match only once in loop in apache POI HSSF

I have a spreadsheet containging rows much like this

SomeText1 SomeText2 SomeText3
Tommy Tommy John
Gilaen Tamara Shaz
Tamara Phil Tamara


I want to filter for rows containing 'Tamara' so the rows I should get will be

SomeText1 SomeText2 SomeText3
Gilaen Tamara Shaz
Tamara Phil Tamara


To try to do this I am using the following code

Map<String,String> mapEndoscBarr= new LinkedHashMap<String,String>();
FileInputStream fis = new FileInputStream(new File(filepath));
HSSFWorkbook workBook = new HSSFWorkbook (fis);
HSSFSheet sheet = workBook.getSheetAt (0);

List<HSSFRow> filteredRows = new ArrayList<HSSFRow>();

//Filter by pathology from what I am given
Iterator<Row> rows= sheet.rowIterator();
while (rows.hasNext ()){
HSSFRow row = (HSSFRow) rows.next ();
Iterator<Cell> cells = row.cellIterator ();
while (cells.hasNext ()){
HSSFCell cell = (HSSFCell) cells.next ();
if (cell.toString().contains("Tamara")) {
filteredRows.add(row);
}
}
}


However the loop adds the row everytime the match is found so that I end up with duplicated rows as follows:

SomeText1 SomeText2 SomeText3
Gilaen Tamara Shaz
Tamara Phil Tamara
Tamara Phil Tamara


How can I force just one match so I don't get this duplicate and it matches if Tamara is present anywhere in the row.

S.B S.B
Answer

Just break out of the cell iteration once a match is found in any of the cells:

Map<String,String> mapEndoscBarr= new LinkedHashMap<String,String>();
            FileInputStream fis = new FileInputStream(new File(filepath));
            HSSFWorkbook      workBook = new HSSFWorkbook (fis);
            HSSFSheet         sheet    = workBook.getSheetAt (0);

            List<HSSFRow> filteredRows = new ArrayList<HSSFRow>();

            //Filter by pathology from what I am given
            Iterator<Row> rows= sheet.rowIterator(); 
            while (rows.hasNext ()){
            HSSFRow row = (HSSFRow) rows.next ();  
            Iterator<Cell> cells = row.cellIterator (); 
             while (cells.hasNext ()){
                 HSSFCell cell = (HSSFCell) cells.next (); 
                  if (cell.toString().contains("Tamara")) {
                      filteredRows.add(row);
                      break;
                    }
             }
            }