Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, April 4, 2017

Remove duplicate entries from ArrayList or List without using collection

Remove duplicate entries from ArrayList or List without using collection.


package testMavProject;

import java.util.ArrayList;

public class removeDuplicate {

public static void main(String[] args) {
// Create a ArrayList type of Integer or other datatype.
ArrayList<Integer> aList=new ArrayList<Integer>();
aList.add(5);
aList.add(7);
aList.add(5);
aList.add(6);
for(int i=0;i<aList.size();i++){
for(int j=i+1;j<aList.size();j++)
{
//Check for duplicate value using if condition
//If you are comparing Integer then you could use "==" sign; if you have string values then user equals method instead of ==. 
if(aList.get(i)==(aList.get(j)))
{
//if values matched then remove the value from J index and back your J index to previous index J--
aList.remove(aList.get(j));
j--;
}
}
}
//Print your list without duplicate value.
System.out.println(aList);
}

}

Popular Posts