remove Duplicates From ArrayList of String - Java java.lang

Java examples for java.lang:String Array

Description

remove Duplicates From ArrayList of String

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Main {
    public static ArrayList<String> removeDuplicatesFromStrings(
            ArrayList<String> a_master) {
        ArrayList<String> a = new ArrayList<String>(a_master);
        Set<String> set = new HashSet<String>();
        List<String> newList = new ArrayList<String>();
        for (Iterator<String> iter = a.iterator(); iter.hasNext();) {
            String element = iter.next();
            if (set.add(element))
                newList.add(element);//  w  ww. ja v a  2  s .com
        }
        a.clear();
        a.addAll(newList);
        return a;
    }
}

Related Tutorials