I have two almost identical methods which filter the list and returns the filtered result. Their algorithm is identical, the difference is that the first function returns the most frequent element and the second returns the least frequent:
private static List<List<Character>> filter(List<List<Character>> lines, int charIndex) {
List<List<Character>> result = copyList(lines);
List<List<Character>> startWith0 = new ArrayList<>();
List<List<Character>> startWith1 = new ArrayList<>();
for(int i = 0; i < result.size(); i++) {
List<Character> currentLine = result.get(i);
if (currentLine.get(charIndex) == '1') {
startWith1.add(currentLine);
} else if (currentLine.get(charIndex) == '0') {
startWith0.add(currentLine);
}
}
if (startWith1.size() > startWith0.size() ||
startWith1.size() == startWith0.size()) {
return startWith1;
} else {
return startWith0;
}
}
The end of the second function looks like this:
if (startWith1.size() > startWith0.size() ||
startWith1.size() == startWith0.size()) {
return startWith0;
} else {
return startWith1;
}
I think that this duplication of code is not a good program design but I don't see the good way to divide the first part of the function and second one into the different methods.