Tuesday, 23 September 2014

Duplicate elements in ArrayList by avoiding Distinct elements

In an Array list I mean to show is the elements which are repeating and by avoiding the distinct elements .To show this we require a piece of code.
Example:
package Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateNumbers {

    public static void main(String[] args) {
   
    ArrayList<String>list = new ArrayList<String>();

    //list of numbers added in from 0-9
   
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        //another set of numbers from 0-5
        for (int i = 0; i < 5; i++) {
            list.add(String.valueOf(i));
        }

        System.out.println("My List : " + list);
        System.out.println("\nHere are the duplicate elements from list : " + findDuplicates(list));
    }

    public static Set<String> findDuplicates(List<String> listContainingDuplicates) {

        final Set<String> setToReturn = new HashSet<String>();
        final Set<String> set1 = new HashSet<String>();

        for (String yourInt : listContainingDuplicates) {
            if (!set1.add(yourInt)) {
                setToReturn.add(yourInt);
            }
        }
        return setToReturn;
    }
}



Output:

My List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]

Here are the duplicate elements from list : [3, 2, 1, 0, 4]

To know FAQ's in Interviews on Selenium Please  ClickHere
To know more on SQL Queries Required For Testers Please ClickHere

No comments:

Post a Comment