Last active
September 13, 2018 06:43
-
-
Save muzafferyilmaz/ad9ad10c1f167410e54097a790d4b44e to your computer and use it in GitHub Desktop.
Search manager for lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.text.Normalizer; | |
import java.util.ArrayList; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.StringTokenizer; | |
/** | |
* Created by Muzaffer YILMAZ on 28.2.2018. | |
*/ | |
public class SearchManager<T extends SearchManager.Searchable> { | |
public interface Searchable { | |
String[] getSearchableFields(); | |
} | |
private ArrayList<T> mList; | |
private static final int MIN_WORD_LENGTH = 1; | |
public SearchManager(ArrayList<T> list) { | |
mList = list; | |
} | |
public List<T> getFilteredList(String expr) { | |
LinkedList<String> tokens = getTokens(expr); | |
// if there is an suitable expression | |
if (tokens == null || tokens.size() == 0) { | |
return mList; | |
} | |
ArrayList<T> retList = new ArrayList<>(); | |
for (T item : mList) { | |
// search each token of expression | |
boolean found = false; | |
for (String token : tokens) { | |
// if any word is found, add return list | |
for (String field : item.getSearchableFields()) { | |
if (isContain(field, token)) { | |
retList.add(item); | |
found = true; | |
break; | |
} | |
} | |
if (found) break; | |
} | |
} | |
return retList; | |
} | |
private String normalize(String token) { | |
// normalize string: iğüş -> IGUS | |
String normalizedToken = Normalizer.normalize(token, Normalizer.Form.NFD); | |
normalizedToken = normalizedToken.replaceAll("(?s)\\p{InCombiningDiacriticalMarks}", ""); | |
return normalizedToken; | |
} | |
private LinkedList<String> getTokens(String expr) { | |
StringTokenizer tokenizer = new StringTokenizer(expr, " "); | |
LinkedList<String> tokens = new LinkedList<>(); | |
while (tokenizer.hasMoreTokens()) { | |
String token = normalize(tokenizer.nextToken().toLowerCase()); | |
if (token.length() >= MIN_WORD_LENGTH) { | |
tokens.add(token); | |
} | |
} | |
return tokens; | |
} | |
private boolean isContain(String item, String expr) { | |
return item != null && normalize(item.toLowerCase()).contains(expr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment