Prabhakar Manthena
Prabhakar Manthena

Reputation: 2303

What is the most efficient way to find and print the duplicate values in arraylist?

For Example,

I have an ArrayList like this,

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

list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("A");
list.add("C");
list.add("A");
list.add("D");
list.add("C");
list.add("D");

I just want to know is there any in built method to find the duplicate values.?

Upvotes: 0

Views: 2467

Answers (4)

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

you can do like this.

int count = Collections.frequency(list,"A");
if(count>1)
System.out.println(count);

update

List<String> duplicates= new ArrayList<String>();
for (String string : list) {
       if(Collections.frequency(list,string)>1&&!duplicates.contains(string)){
            duplicates.add(string);
       }
}

System.out.println(duplicates);

output

[A, C, D]

Upvotes: 1

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

You can use Set.add(...) return value for this. Add would return false if the set already contains the value being added. Here's how you'd use it:

void printDuplicates(List<String> data) {
  Set<String> uniques = new HashSet<String>(data.size() * 2);
  for (String s: data) {
    if (!uniques.add(s)) {
      System.out.println("Duplicate: " + s);
    }
  }
}

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

There is no such a method in ArrayList. You can use Map to detect duplicates.

Map<String, Integer> map = new HashMap<>();
...
Integer n = map.get(s);
map.put(s, n == null ? 1 : n + 1);

Upvotes: 2

Surinder ツ
Surinder ツ

Reputation: 1788

The method add of Set returns a boolean whether a value already exists (true if it does not exist, false if it already exists.

So just iterate through all the values:

public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)
{ 
  final Set<Integer> setToReturn = new HashSet(); 
  final Set<Integer> set1 = new HashSet();

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

Upvotes: 3

Related Questions