Thursday, 1 August 2013

Find the Duplicate element from ArrayList in Java

How To Find the Duplicate element in ArrayList(Simple Approach).

Here i am taking an simple approach to do this.

Car.java

public class Car {

public int model;
public String name;

public Car()
{

}

public int getModel() {
return model;
}
public void setModel(int model) {
this.model = model;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public boolean equals(Object obj) {  
Car carObj=null;  
if(obj instanceof Car){  
carObj=(Car)obj;  
}  
if(carObj!=null && (this.model==carObj.model) && (this.name.equals(carObj.name))){  
return true;  
}  
return false;  
}  

public String toString() {
       return ("Car Model: " + model + "and" +
       "Car Name: " + name);
   }

}



CarImpl.java
public class CarImpl{


public static void main(String[] args) {

System.out.println("Get the Duplicate Element in a list");
Car c=new Car();
c.setModel(1);
c.setName("Honda");

Car c1=new Car();
c.setModel(11);
c.setName("Hyundai");

List<Car> listcar=new ArrayList<Car>();
listcar.add(c);
listcar.add(c);
listcar.add(c);
listcar.add(c1);

for(int i=0;i<listcar.size();i++)
{
for(int j=0;j<i;j++)
{
if(listcar.get(j).equals(listcar.get(i)))
{
System.out.println("Dupliacte Object are" + listcar.get(i).toString());
}
}

}

/*Map<Car, Integer> counts = new HashMap<Car, Integer>();

for (Car str : listcar) {
   if (counts.containsKey(str)) {
       counts.put(str, counts.get(str) + 1);
   } else {
       counts.put(str, 1);
   }
}

for (Map.Entry<Car, Integer> entry : counts.entrySet()) {
   System.out.println(entry.getKey() + " = " + entry.getValue());
}

*/

}
}

This is very simple approach to find out the duplicate element in list.

# Commented code also worked.

@I hope you will like my Blog and post.Any suggestion must be appreciated.

No comments:

Post a Comment

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...