
How do i find duplicates in ArrayList. First i add some elements to ArrayList, then how do i find the duplicates and show the duplicate elements. Give an example

import java.util.*;
class FindDuplicates
{
public static <T> List getDuplicate(Collection<T> list) {
final List<T> l = new ArrayList<T>();
Set<T> set = new HashSet<T>() {
public boolean add(T e) {
if (contains(e)) {
l.add(e);
}
return super.add(e);
}
};
for (T t : list) {
set.add(t);
}
return l;
}
public static <T> boolean hasDuplicate(Collection<T> list) {
if (getDuplicate(list).isEmpty())
return false;
return true;
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("How many elements do you want to add in a list: ");
int no=input.nextInt();
ArrayList<String> list=new ArrayList<String>();
for(int i=0;i<no;i++){
String st=input.next();
list.add(st);
}
System.out.println("Duplicate Elemnts are: ");
if(hasDuplicate(list)){
List l=getDuplicate(list);
for(int i=0;i<l.size();i++){
System.out.println(l.get(i).toString());
}
}
else{
System.out.println("There is no duplicate elements in the list.");
}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.