📜 ⬆️ ⬇️

Search for changes in two collections

Good night community.

In the current project I'm working on, it became necessary to identify changes in the two data collections. If in a nutshell, the List of orders comes from the Server and the same List of orders is in the database. It is necessary to determine how many orders have been added, updated and deleted in the new collection. Interested please under the cat.


')
It seems like a trivial task you say and you will be right! But I have not slept for 3 days, so initially my code turned out in 3 cycles. Bullshit Bullshit I thought and started over. I will not even give the code :)

Half an hour later the class was born in 2 cycles - we are passing according to the new data and we consider the new and updated ones, then we go through the old ones and we consider the deleted ones. I will not give the code either, because I immediately wanted to fit everything in one cycle and, on the advice of one article, I got rid of the class I had just written.

So, after another 30 minutes, I wrote the CollectionChangeCouner class, the algorithm of which, in my opinion, is optimal.

Listing
import java.util.Iterator; import java.util.List; /** * Created by vitaliy on 18.03.2016. * */ public class CollectionChangeCouner<T> { private int inserted; private int updated; private int deleted; public CollectionChangeCouner(List<T> oldData, List<T> newData) { Iterator<T> oldDataIterator = oldData.iterator(); while (oldDataIterator.hasNext()) { T oldItem = oldDataIterator.next(); int index = newData.indexOf(oldItem); if (index < 0) { deleted++; oldDataIterator.remove(); } else { final T newItem = newData.get(index); if (!oldItem.equals(newItem)) { updated++; } newData.remove(index); } } inserted = newData.size(); } public int inserted() { return inserted; } public int updated() { return updated; } public int deleted() { return deleted; } public boolean hadChangedData() { return (inserted > 0) || (updated > 0) || (deleted > 0); } } 



Everything seems to be on this :)
I hope someone will help my mini article about anything, or maybe clever zahabrennye uncles suggest a better option. But I'm afraid I'll read about it tomorrow.

PS Sleep more and more, it is useful!

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


All Articles