September 26, 2018

Removing duplicate values from ArrayList in Java

/**
 * This is a sample java program
 * that demonstrate removing duplicate elements from an ArrayList
 *
 * 2 ways - one by using set and other by Iterating through each objects
 *
 * List Interface is implemented by ArrayList, LinkedList, Vector and Stack classes
 *
 */
package com.belazy.collections;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Saurav
 *
 *
 * @version 1.6
 *
 */
public class RemoveDuplicates {

/**
* @param args
*/
public static void main(String[] args) {

List<String> orgList = new ArrayList<String>();
orgList.add("SACHIN");
orgList.add("SACHIN");
orgList.add("ANJALI");
orgList.add("SARA");
orgList.add("ARJUN");

List<String> processedList = new ArrayList<String>();

for(String str:orgList){
if(!processedList.contains(str)){
processedList.add(str);
}
}


Set<String> newSet = new LinkedHashSet<String>(orgList);

System.out.println(" Orginal List : "+orgList);
System.out.println(" After Removing duplicates : "+processedList);
System.out.println(" New Set : "+newSet);



}

}



Output

 Orginal List : [SACHIN, SACHIN, ANJALI, SARA, ARJUN]
 After Removing duplicates : [SACHIN, ANJALI, SARA, ARJUN]
 New Set : [SACHIN, ANJALI, SARA, ARJUN]

No comments:

Post a Comment

Your feedback may help others !!!

Facebook comments