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.
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() .
ArrayList allows duplicate values in its collection. On other hand duplicate elements are not allowed in Hashset.
Try this...
ArrayList<String> values=new ArrayList<String>(); HashSet<String> hashSet = new HashSet<String>(); hashSet.addAll(values); values.clear(); values.addAll(hashSet);
Try below code,
ArrayList<String> values=new ArrayList<String>(); String newValue; // repeated additions: if (!values.contains(newValue)) {values.add(newValue);}
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