Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove Duplicate value from arraylist in Android [duplicate]

ArrayList<String> values=new ArrayList<String>(); values.add("s"); values.add("n"); values.add("a"); values.add("s"); 

In this Array, I want to remove repeated values.

like image 332
Kumar Avatar asked Dec 10 '09 09:12

Kumar


People also ask

How do you remove duplicates from an ArrayList in Java 8?

To remove the duplicates from the arraylist, we can use the java 8 stream api as well. Use steam's distinct() method which returns a stream consisting of the distinct elements comparing by object's equals() method. Collect all district elements as List using Collectors. toList() .

Can an ArrayList have duplicate elements?

ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.


2 Answers

Try this...

    ArrayList<String> values=new ArrayList<String>();     HashSet<String> hashSet = new HashSet<String>();     hashSet.addAll(values);     values.clear();     values.addAll(hashSet); 
like image 187
Silambarasan Poonguti Avatar answered Sep 22 '22 02:09

Silambarasan Poonguti


Try below code,

ArrayList<String> values=new ArrayList<String>(); String newValue;  // repeated additions: if (!values.contains(newValue)) {values.add(newValue);} 
like image 24
Freyr Avatar answered Sep 24 '22 02:09

Freyr