How to compare two List of String in Java?

UPDATED: 25 November 2014
List: Collections Framework Java


The best approach to compare two List<String>

Source Code
import java.util.ArrayList;
import java.util.List;

/**
 * @author javaQuery
 */
public class CompareTwoListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString1 = new ArrayList<String>();
        /* Add element from 0th position */
        listString1.add("a");
        listString1.add("b");
        listString1.add("c");
        listString1.add("d");
        listString1.add("e");

        /* Print list */
        System.out.println("Initial List1:\n" + listString1);
        System.out.println("---------------------------------");

        /* Create list of String */
        List<String> listString2 = new ArrayList<String>();
        /* Add element from 0th position */
        listString2.add("e");
        listString2.add("d");
        listString2.add("c");
        listString2.add("a");
        listString2.add("b");
        
        /* Print list */
        System.out.println("Initial List2:\n" + listString2);
        System.out.println("---------------------------------");

        if(listString1 != null && listString2 != null && (listString1.size() == listString2.size())){
            listString1.removeAll(listString2);
            if(listString1.isEmpty()){
                System.out.println("Both list are same.");
            }else{
                System.out.println("Both list are not same");
            }
        }
    }
}

Output
Initial List1:
[a, b, c, d, e]
---------------------------------
Initial List2:
[e, d, c, a, b]
---------------------------------
Both list are same.

0 comments :