On Java Development

All things related to Java development, from the perspective of a caveman.

Reconciling ArrayList contents with the Comparator class

without comments


This post explains how to use the Comparator class to reconcile the contents of two arraylists. As an example of use, this technique can be helpful when there is a need to know what was changed in a pick list. This information can then be used to log the “who-what-when” questions about the edit session.


The Problem

The web-page had the usual input text boxes and a so called “pick list” component. This component has a list of entries on its left side and a list of entries located on the right side. The list on the right contains any entries that were selected from the list of items on the left. The problem arises when there is a need to capture what was added and what was removed from the picked list. This information can be obtained by comparing the lists against each other.


The Brute Force Solution

This solution uses two ArrayLists. The first (named “preservedSelectedValues”) holds the list of items in the pick list BEFORE changes. The second (named “selectedValues”), holds the list of items after changes. Both ArrayLists hold those entries as SelectItem objects.

The solution presented below reeks of approaches seen in COBOL or RPG programs.


There is a better way

The better way is to create a comparator class which has dual responsibilities. The first responsibility is to sort the ArrayLists. The second responsibility is to compare the two lists against each other to determine differences between them.

The comparator class accepts 2 objects and then casts them into SelectItem objects to perform compares against the value properties. The returned value from this exercise is an integer reporting whether it was found to be less than, equal to or greater than.

The comparator class

The implementation takes place in the application and uses the SelectItemComparator class presented above. The code below sorts the array lists followed by the comparison operations. For this example, the results are printed to the console and shows which items were deleted and added.

There. Much better.

Written by admin

March 11th, 2016 at 1:20 pm

Leave a Reply

You must be logged in to post a comment.