refactoring code with comparator