Reputation: 20391
My question is similar to: java Best way to Filter list of object
I have a list of objects say Sales. I want only the Sales objects whose Product matches the ones in another list, say saleProductList.
Other than looping, is there a better way to do it.
However I wish to be able to able to do the filtering with code accessible to android, e.g. The libraries would need to play nice with the android OS and run on the android OS. I'm hoping to avoid making home cooked code for a problem I assume is common, any suggestions?
Upvotes: 8
Views: 20420
Reputation: 345
// mFinalList will contain filtered data.
List<Object> mFinalList=new ArrayList<>();
for (Object person : listData) {
if (person.getNameType().equalsIgnoreCase("somename")) {
mFinalList.add(person);
}
}
Upvotes: 11
Reputation: 6485
If your goal is to filter a list (List
or ArrayList
) on a simple constraint and diplay the data in a ListView
you can directly use the interface Filterable
in your adapter as below:
public class AdapterFilterable extends BaseAdapter implements Filterable {
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.values != null) {
_arrayList = (List<object>) results.values;
}
else {
_arrayList = ApplicationGlobal._dataManager.get_ArraylistFull();
}
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<YourObject> filteredList = new ArrayList<YourObject>();
//Do your filtering operation with the constraint String
//Return result for publishResults to use it
results.count = filteredList.size();
results.values = filteredList;
return results;
}
};
return filter;
}
To use the filter, like when searching in a list or just filtering it with a constraint, you just need:
_yourAdapter.getFilter().filter(String yourConstraintString);
Else if you want to filter on complex data you can simply filter with a for
loop and then do your notifyDataChanged();
.
Hope it helps.
Upvotes: 6