Search code examples
javamethodscode-duplication

Java prevent method duplication for same purpose - different parameters


I have 2 methods that are almost identical. I'd like to know if there is a way to combine these 2 methods into 1, which would allow me to take both types of maps as a parameter. The methods writes to an excel file. The key is the excel header (all keys go in first row) and the mapped list are everything beneath each key (the data). Any unique ideas?

private void test(Sheet sheet, HashMap<String, List<Double>> map) {
        for (String var : map.keySet()) {
            int rowNumb=0;
            Row row = sheet.getRow(rowNumb);
            Cell cell = row.createCell(currColumn);
            cell.setCellValue(var);
            rowNumb++;
            List<Double> list = map.get(var);
            for (int i = 0; i < list.size(); i++) {
                row = sheet.getRow(rowNumb);
                cell = row.createCell(currColumn);
                cell.setCellValue(list.get(i));
            }
            currColumn++;
        }
    }



private void test(Sheet sheet, HashMap<String, List<String>> map) {  <-- takes in String list rather thand Double.
        for (String var : map.keySet()) {
            int rowNumb=0;
            Row row = sheet.getRow(rowNumb);
            Cell cell = row.createCell(currColumn);
            cell.setCellValue(var);
            rowNumb++;
            List<String> list = map.get(var);         <---- Only thing that is different
            for (int i = 0; i < list.size(); i++) {
                row = sheet.getRow(rowNumb);
                cell = row.createCell(currColumn);
                cell.setCellValue(list.get(i));
            }
            currColumn++;
        }
    }

Solution

  • You should use generics:

    private <T> void test(Sheet sheet, HashMap<String, List<T>> map) {
        for (String var : map.keySet()) {
            List<T> list = map.get(var);
            for (int i = 0; i < list.size(); i++) {
                row = sheet.getRow(i);
                cell = row.createCell(currColumn);
                cell.setCellValue(list.get(i));
            }
            currColumn++;
        }
    }
    

    Whereever you previously put any reference to String and Double now put T.