Saturday, November 1, 2014

Check for duplicates in a List

A List typically allow duplicate elements. List is an ordered collection interface.

If you want to prevent duplicates, you would typically want to use a Set. If maintaining order is needed, use LinkedHashSet.

However, there are instances where you want to use a List and prevent duplicate elements when adding to the list.

You can check for duplicates in the List by using the HashSet(list) technique outlined below.


You should first override equals() and hashcode() methods in your class.

public class IncentiveVB implements Serializable  {

 private static final long serialVersionUID = 1L;
 

 private String incentiveId;
 
 private String incentiveName;
 
 private String incentiveCode;
 
 private String inputType; 
 
 /*
  * getters and setters here
  */
 
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result
    + ((incentiveId == null) ? 0 : incentiveId.hashCode());
  result = prime * result
    + ((incentiveName == null) ? 0 : incentiveName.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  IncentiveVB other = (IncentiveVB) obj;
  if (incentiveId == null) {
   if (other.incentiveId != null)
    return false;
  } else if (!incentiveId.equals(other.incentiveId))
   return false;
  if (incentiveName == null) {
   if (other.incentiveName != null)
    return false;
  } else if (!incentiveName.equals(other.incentiveName))
   return false;
  return true;
 } 
}


Here's a few ways you can override the equals() and hashCode() methods

Then, in your code check for duplicates in the list before actually adding an object into the list as shown below.

List<IncentiveVB> incentiveVBList = ....;
 
for (condition...) {

 /*
  * code to create 'incentiveVB' object here
  */

 //check for duplicates of this IncentiveVB in the list before adding to the list
 //by testing a copy of your List against a HashSet
 List<IncentiveVB> list = new ArrayList<IncentiveVB>(incentiveVBList);
 list.add(incentiveVB);
 Set<IncentiveVB> set = new HashSet<IncentiveVB>(list);
 if(set.size() < list.size()){
  //there are duplicates of this IncentiveVB in the list. don't add.
  continue;
 }
 incentiveVBList.add(incentiveVB);
}



No comments:

Post a Comment