Is there a more efficient way to check for duplicate values ​​(Java)?

I need to check that the list of identifiers does not contain duplicate values. My attempt to do this can be shown here:

public void validate(RecordCollection collection) throws BusinessException { LinkedHashMap<Long, Long> existingIds = new LinkedHashMap<Long, Long>(); for (Record record : collection.getArrayList()) { // check that you don't have two records with the same id if (existingIds.containsKey(record.getID())) { throw new BusinessException("records must be unique.", ExceptionCodes.RECORDS_MUST_BE_UNIQUE); } //add the id to the map of existing ids existingIds.put(record.getID(), vo.getID()); } 

Is there a more efficient way to implement this check?

+4
source share
3 answers

Yes, there is only a small modification:

 for (Record record : collection.getArrayList()) if (existingIds.put(record.getID(), vo.getID()) != null) throw new BusinessException("records must be unique.", ExceptionCodes.RECORDS_MUST_BE_UNIQUE); 
Operation

A Map .put() returns the previous value for the key. If there was no record, null returned. And here, since you do not have null values, this means that if the return code is NOT null , you have a duplicate.

(also why a LinkedHashMap ? Your method returns void , so the insertion order doesn't matter, just use a HashMap )

(also, as suggested, when building a map, initialize its size to the size of the collection that you are checking)

+4
source

In this case, I would think of a set of identifiers. The add method returns a boolean if the value already exists or not.

That way you can use the collection anywhere, and if the addition returns false, you throw an exception.

About the implementation: RecordCollection should be Set and check the identifiers on it. Thus, the validation method is a private part of the RecordCollection, and when an item is added, an exception will be thrown if necessary. The verification cycle is completely excluded.

If you cannot add validation to the collection, then there is a subclass of "IdenticalIDRecordCollection"

+2
source
  Set set=new HashSet<>(collection.getArrayList()); System.out.println(x.size()==set.size()); 

prints true if there are no dublicates

+1
source

Source: https://habr.com/ru/post/1484808/


All Articles