How to combine two similar methods in java?

H294 :

I have two methods, they are different in their conditions. So how I can combine two methods into one?

private void filterById(String keyW) {
    neModel.setRowCount(0);
    for (int i = neList.size() - 1; i > -1; i--) {
        //CONDITION:
        if (String.valueOf(neList.get(i).getId()).toLowerCase().contains(keyW.toLowerCase())) {
            Object[] aRow = createARow(i);
            neModel.addRow(aRow);
        }
    }
}

private void filterByTitle(String keyW) {
    neModel.setRowCount(0);
    for (int i = neList.size() - 1; i > -1; i--) {
        //CONDITION:
        if (neList.get(i).getTitle().toLowerCase().contains(keyW.toLowerCase())) {
            Object[] aRow = createARow(i);
            neModel.addRow(aRow);
        }
    }
}

*'neList' ia an ArrayList of 'News' . Class 'News' has properties: id, title, text, etc.

Thomas :

With Java 8+, you could try to use a functional interface and pass the differences as a strategy.

Something like this (untested as I don't have a compiler atm):

private void filter(String keyW, Function<News, String> propertyExtractor) {
  neModel.setRowCount(0);

  //note that this could probably be replaced by for(News news : newList)
  //but in that case you'd either have to change createARow to not need the index or increment the index in the loop body
  for (int i = neList.size() - 1; i > -1; i--) {        
    if (propertyExtractor.apply(neList.get(i)).toLowerCase().contains(keyW.toLowerCase())) {
        Object[] aRow = createARow(i);
        neModel.addRow(aRow);
    }
  }
}

//Examples of how to use it, you don't have to keep those (delegating) methods
private void filterById(String keyW) { 
  filter( keyW, e -> String.valueOf(e.getId()));
}

private void filterByTitle(String keyW) { 
  filter( keyW, News::getTitle);
  //or: filter( keyW, e -> e.getTitle());
}

Alternatively instead of a Function<T, S> pass in a Predicate<T> which provides the entire condition and just do if(predicate.test(neList.get(i))) { ... }.

Edit: replaced T with News as per the OP's comment

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102238&siteId=1