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?
If we want to filter using element index or position, we have to use filterIndexed(). filterIndexed() function takes a predicate with two arguments: index and the value of an element. We can filter the collections by negative conditions by using filterNot().
To filter collections by negative conditions, use filterNot() . It returns a list of elements for which the predicate yields false . There are also functions that narrow the element type by filtering elements of a given type: filterIsInstance() returns collection elements of a given type.
Android OS uses filters to pinpoint the set of Activities, Services, and Broadcast receivers that can handle the Intent with help of specified set of action, categories, data scheme associated with an Intent.
// mFinalList will contain filtered data.
List<Object> mFinalList=new ArrayList<>();
for (Object person : listData) {
if (person.getNameType().equalsIgnoreCase("somename")) {
mFinalList.add(person);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With