I have a piece of code from an old project.
The logic (in a high level) is as follows:
The user sends a series of {id,Xi} where id is the primary key of the object in the database.
The aim is that the database is updated but the series of Xi values is always unique.
I.e. if the user sends {1,X1} and in the database we have {1,X2},{2,X1} the input should be rejected otherwise we end up with duplicates i.e. {1,X1},{2,X1} i.e. we have X1 twice in different rows.
In lower level the user sends a series of custom objects that encapsulate this information.
Currently the implementation for this uses “brute-force” i.e. continuous for-loops over input and jdbc resultset to ensure uniqueness.
I do not like this approach and moreover the actual implementation has subtle bugs but this is another story.
I am searching for a better approach, both in terms of coding and performance.
What I was thinking is the following:
- Create a
Setfrom the user’s input list. If theSethas different size than list, then user’s input has duplicates.Stop there. - Load data from jdbc.
- Create a
HashMap<Long,String>with the user’s input. The key is the primary key. - Loop over result set. If
HashMapdoes notcontaina key with the same value as ResultSet’s row id then add it toHashMap - In the end get
HashMap‘s values as aList.If it contains duplicates reject input.
This is the algorithm I came up.
Is there a better approach than this? (I assume that I am not erroneous on the algorithm it self)
Since you can’t change the database, as stated in the comments. I would probably extend out your Set idea. Create a
HashMap<Long, String>and put all of the items from the database in it, then also create aHashSet<String>with all of the values from your database in it.Then as you go through the user input, check the key against the hashmap and see if the values are the same, if they are, then great you don’t have to do anything because that exact input is already in your database.
If they aren’t the same then check the value against the HashSet to see if it already exists. If it does then you have a duplicate.
Should perform much better than a loop.
Edit:
For multiple updates perform all of the updates on the
HashMapcreated from your database then once again check theMap‘s value set to see if its’ size is different from the key set.There might be a better way to do this, but this is the best I got.