How to Compare Two List in Java

Compare Two List in Java

In this example, We will show you sample program about, How to compare two list in Java. The example program has been tested and output shared in the same post.

Example Program

package com.dineshkrish;

import java.util.List;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class ListUtil {

	public static boolean compare(List<?> list1, List<?> list2) {
		
		if(list1 == null || list2 == null)
			return false;
		
		if(list1.size() != list2.size())
			return false;
		
		if(list1.containsAll(list2))
			return true;
		
		return false;
	}
}

Testing the ListUtil.compare() method in the CompareList class.

package com.dineshkrish;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class CompareList {

	
	public static void main(String[] args) {
		
		// list object 1
		List<String> list1 = new ArrayList<String>();
		
		list1.add("One");
		list1.add("Two");
		list1.add("Three");
		list1.add("Four");
		list1.add("Five");
		
		// list object 2
		List<String> list2 = new ArrayList<String>();
		
		list2.add("One");
		list2.add("Two");
		list2.add("Three");
		list2.add("Four");
		list2.add("Five");
		
		if(ListUtil.compare(list1, list2)) {
			
			System.out.println("Equal");
		} else {
			
			System.out.println("Not Equal");
		}
		
	}
}

Output

Equal

References

1. JavaDoc – List Interface
2. JavaDoc – ArrayList Class

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.