Java Tool To Compare Two Lists and Spit Out The Differences – Working Example

As a heavy java programmer, most of the time I encounter a problem where I have two lists and need to find out the differences between these two. One of the ways I sometimes quickly find out the difference is:

  • To print out the list and then use microsoft excel to compare the two columns.
  • Upload the file to temporary database tables and the run SQL query to find out the difference

As I started encountering the list compare more often, I thought of writing a tool that takes two lists and then simply print out the differences. Thus I coded the following simple piece of java program to achieve this.

The following program:

  • Can take an input of two ArrayLists presumably containing Strings, numbers of mix of both
  • It then compares the two lists and then prints out all items from first list which are not in the second lists and also prints out the items in second lists which are not in the first list

I can now use this program as often as I want and solves the hassle of me having to upload the data to database for compare or even import to excel to do the same.

Most of the programs from my blog come from my real world working experience. They are simple programs but sometimes save your huge time. Feel free to copy and modify any of the programs for your own use. Everything is open sourced and free in my blog

package com.kushal.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Kushal Paudyal Last Modified On 2011-09-16
 * 
 *         This simple utility compares two String or number lists or a list
 *         that contains either strings or number and then prints out a list of
 *         items that are in first list but not in the second list and also a
 *         list of items that are in second list but not in the first list.
 */
public class ListCompare {

	public static void main(String args[]) {
		List listA = new ArrayList();
		listA.add(1);
		listA.add(2);
		listA.add("Kushal");
		listA.add("Madan");
		listA.add("Pooja");
		listA.add("Kripa");

		List listB = new ArrayList();
		listB.add(2);
		listB.add(3);
		listB.add("Kushal");
		listB.add("Madan");
		listB.add("Jenny");
		listB.add("Betsy");

		ListCompare listComp = new ListCompare();
		listComp.compareLists(listA, listB);

	}

	public void compareLists(List firstList, List secondList) {
		Map mapForFirstList = new HashMap();
		Map mapForSecondList = new HashMap();
		Iterator firstListIterator = firstList.iterator();
		Iterator secondListIterator = secondList.iterator();
		while (firstListIterator.hasNext()) {
			String firstListKeyValue = firstListIterator.next().toString();
			/**
			 * Put the value from the list into the map, only if the same value
			 * already does not exists. That means if there are duplicates, we
			 * put only one instance into the hashmap.
			 */
			if (!mapForFirstList.containsKey(firstListKeyValue)) {
				mapForFirstList.put(firstListKeyValue, firstListKeyValue);
			}

		}

		while (secondListIterator.hasNext()) {
			String secondListKeyValue = secondListIterator.next().toString();
			/**
			 * Put the value from the list into the map, only if the same value
			 * already does not exists. That means if there are duplicates, we
			 * put only one instance into the hashmap.
			 */
			if (!mapForSecondList.containsKey(secondListKeyValue)) {
				mapForSecondList.put(secondListKeyValue, secondListKeyValue);
			}

		}
		compareAndPrintResults(mapForFirstList, mapForSecondList);

	}

	private void compareAndPrintResults(Map mapForFirstList,
			Map mapForSecondList) {
		/** Compare first map against the second one and print the difference **/
		printItemsFromFirstListThatAreNotOnSecondList(mapForFirstList,
				mapForSecondList);
		/** Compare second map against the first and print the difference */
		printItemsFromSecondListThatAreNotOnFirstList(mapForSecondList,
				mapForFirstList);

	}

	private void printItemsFromFirstListThatAreNotOnSecondList(Map mapA,
			Map mapB) {
		System.out
				.println("***Items from first list that are not in second list");
		doComparisionAndPrint(mapA, mapB);

	}

	private void printItemsFromSecondListThatAreNotOnFirstList(Map mapA,
			Map mapB) {
		System.out
				.println("***Items from second list that are not in firstList list");
		doComparisionAndPrint(mapA, mapB);

	}

	/**
	 * @param mapA
	 * @param mapB
	 * 
	 *            This method compares two hashmaps and prints out the values
	 *            from the first one that are not in the second one.
	 */
	private void doComparisionAndPrint(Map mapA, Map mapB) {
		// both maps should be non-empty for comparison.
		if (mapA != null && mapB != null) {
			Iterator mapAIterator = mapA.keySet().iterator();

			while (mapAIterator.hasNext()) {
				String key = mapAIterator.next().toString();
				if (!mapB.containsKey(key)) {
					System.out.println(key);
				}
			}
		}
	}
}

The following is the output of this program:

		***Items from first list that are not in second list
		1
		Kripa
		Pooja
		***Items from second list that are not in firstList list
		3
		Betsy
		Jenny
[My Video Promotion]
  1. How to extract plain Text from HTML Website easily in Java
  2. Binary Search Implementation In Java
  3. Simple Implemenation Of Stack In Java Using Vector
  4. How To Find What Java Version You Are Using?
  5. Computing the total, free and usable disk space easily using JDK 1.6
  6. Creating java.util.date and java.util.sql objects from Calendar object
  7. Bar Code Generation In Java Using iText API
  8. Simple Tag Generator In Java For Music Blogs
  9. Tutorial on Converting an List of Strings or Numbers to a CSV file with optional sorting
  10. Calling URL Browser From Java Application
  11. Java Reflection Tutorial – List Methods Of A Class
  12. Cleaning Punctuation And White Spaces From A String
  13. Java Tutorial – Using JCIFS to copy files to shared network drive using username and password
  14. Prime Number Finder In Java
  15. Utility Class For Getting SQL Connection and Closing It
  16. Java Design Pattern – Singleton Pattern
  17. Reading / Writing File in Java and String Manipulation
  18. How to capture a screenshot using Java and save it to a file?
  19. Calculating The Difference Between Two Dates In Terms of Months
  20. Getting The Name Of Currently Logged In User In The System
  21. How To Set And Get System Clipboard Contents In Java
  22. RGB To Hex and Hex To RGB Conversion Using Java and Regular Expressions
  23. Java Code Implementation Of Selection Sort
  24. Generating Nepali Unicode Sequence For Characters
  25. Java Tool To Compare Two Lists and Spit Out The Differences – Working Example
  26. Replacing non-ASCII characters using Java Regular Expressions
  27. Calculating Folder Size In Java
Tagged , , , , , , , , . Bookmark the permalink.

3 Responses to Calculating Folder Size In Java

  1. Pingback: Sanjaal.com » Latest Updates

  2. Jamie says:

    This approach uses less memory:

    public static class SizeCounter implements FileFilter
    {
    private long total = 0;
    public SizeCounter(){};
    public boolean accept(File pathname) {
    if ( pathname.isFile()) {
    total+=pathname.length();
    } else {
    pathname.listFiles(this);
    }
    return false;
    }
    public long getTotal()
    {
    return total;
    }
    }

    private static long getFileOrDirectorySize(File file) {
    SizeCounter counter = new SizeCounter();
    file.listFiles(counter);
    return counter.getTotal();
    }

  3. kushalzone says:

    Thank you Jamie for your optimized solution.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.