Inscrivez-vous ou connectez-vous pour rejoindre votre communauté professionnelle.
//By using Set
int last=arr.length;
Set<Integer> myv=newHashSet<Integer>();for(int i =0; i < last; i++){myv.add(arr[i]);}//display resultIterator it = myv.iterator();while(it.hasNext()){System.out.println(it.next());}
As mentioned above, there are many ways.
1. Copying all the elements of ArrayList to LinkedHashSet.
2. Emptying the ArrayList, you can use clear() method to remove all elements of ArrayList and start fresh.
3. Copying all the elements of LinkedHashSet (non-duplicate elements) to the ArrayList.
USE THE FOR LOOP
ELSE USING ARRAHY CLASS IN COLLECTION
he easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList : List<String> al = new ArrayList<>(); // add elements to al, including duplicates Set<String> hs = new HashSet<>(); hs.addAll(al); al.clear(); al.addAll(hs);
En utilisant un Set (qui n'accepte pas les doublons)
we can use Set for that add ArrayList to HashSet or LikedHashSet then automatically Set remove all duplicate element. or we have another way for that we conver ArrayList to Array and check each and every element using index
The easiest way to remove repeated elements is to add the contents to a Set
List<String> al = new ArrayList<>();
including duplicateSet <String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);
If you don't want duplicates in a Collection, you should consider why you're using a Collectionthat allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set(which will not allow duplicates) and then add the Set back to the ArrayList:
List<String> al =newArrayList<>();// add elements to al, including duplicatesSet<String> hs =newHashSet<>(); hs.addAll(al); al.clear(); al.addAll(hs);
There are many way to do this...
1. With using HashSet:
HashSet: It remove duplicates from the list.
ArrayList<String> arrList = new ArrayList<String>();
// add elements to "arrList", including duplicates
ArrayList<String> remDuplicateList= new ArrayList<String>(new HashSet<String>(arrList));
2. Only using ArrayList:
ArrayList<String> secondList = new ArrayList<String>();
Iterator iterator = arrList.iterator();
while (iterator.hasNext()) {
String o = (String) iterator.next();
if(!secondList.contains(o))
secondList.add(o);
}
which can be used to delete the duplicate elements from arraylist in Java.