Compare two lists for Equal - Java java.util

Java examples for java.util:List Operation

Description

Compare two lists for Equal

Demo Code


//package com.java2s;
import java.util.List;
import java.util.ListIterator;

public class Main {
    public static void main(String[] argv) {
        List left = java.util.Arrays.asList("asdf", "java2s.com");
        List right = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(listEquals(left, right));
    }/*from w  w  w  .j a va 2  s. c o m*/

    public static <T> boolean listEquals(List<T> left, List<T> right) {
        if (left == right)
            return true;

        ListIterator<T> leftIterator = left.listIterator();
        ListIterator<T> rightIterator = right.listIterator();

        while (leftIterator.hasNext() && rightIterator.hasNext()) {
            T leftElement = leftIterator.next();
            T rightElement = rightIterator.next();
            if (!(leftElement == null ? rightElement == null : leftElement
                    .equals(rightElement)))
                return false;
        }
        return !(leftIterator.hasNext() || rightIterator.hasNext());
    }
}

Related Tutorials