How to get Unique values from List of String?

UPDATED: 02 February 2015

This is frequently asked question in Java Interviews for Collection Framework. Question asked to know the basic knowledge of Interviewee.

Source code
public class GetUniqueValuesFromList {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add element from 0th position */
        listString.add("vicky");
        listString.add("chirag");
        listString.add("heer");
        listString.add("riddhi");
        listString.add("chirag");
        
        System.out.println("Initial String List:" + listString);
        System.out.println("------------------------");
        
        /* Create set of String from List */
        /* Set will store only unique values from listString */
        Set<String> setString = new HashSet<String>(listString);
        
        System.out.println("Values in Set:" + setString);
        System.out.println("------------------------");
        
        /* Clear the listString */
        listString.clear();
        
        /* Add setString(Unique) values back to listString */
        listString.addAll(setString);
        
        System.out.println("Unique values in List" + listString);
    }
}

Output
Initial String List:[vicky, chirag, heer, riddhi, chirag]
------------------------
Values in Set:[vicky, riddhi, heer, chirag]
------------------------
Unique values in List[vicky, riddhi, heer, chirag]

0 comments :