Reputation: 39
How can I remove duplicate items in my ArrayList. I am new in android programming and I also tried to study other but it really hard for me to figure out how to eliminate similar items. Some suggestion are using hashmap but I have no idea where to put it. Here's my code.
mAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list);
lvList.setAdapter(mAdapter);
lvList.setOnItemClickListener(this);
schoolIndex.clear();
ArrayList<String> finalFilterList = list;
ArrayList<String> finalSchoolsList = new ArrayList<String>(
Arrays.asList(this.sList));
for (int i = 0; i < finalFilterList.size(); i++) {
for (int o = 0; o < finalSchoolsList.size(); o++) {
if (finalFilterList.get(i).equalsIgnoreCase(
finalSchoolsList.get(o))) {
schoolIndex.add(o);
}
}
}
mAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list);
lvList.setAdapter(mAdapter);
lvList.setOnItemClickListener(this);
if (list.isEmpty()) {
Toast.makeText(getActivity(), "No Hospitals Found",
Toast.LENGTH_SHORT).show();
navi.dia.show();
}
return v;
Upvotes: 0
Views: 3691
Reputation: 5040
If you want to remove duplicates, you can add all elements to a Set and then add them back to the ArrayList but you will lose the order if you use a Set.
As you are using the ArrayList in adapter, I suggest you to use LinkedHashSet, which retains the order
Try this :
List<String> arrayList = new ArrayList<>(); // this will be your arraylist
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.addAll(arrayList);
arrayList.clear();
arrayList.addAll(linkedHashSet);
Upvotes: 2
Reputation: 457
You can remove the Duplicates likes this:
Set<String> set = new HashSet<String>('Your ArrayList');
// Then you can create a new ArrayList, this will be a list with no duplicates
ArrayList<String> newList = new ArrayList<String>(set);
Sorry if this does not answer the question
Upvotes: 0