kodu_
kodu_

Reputation: 39

How to compare two array list of same size and print difference when both are not same in java

I have used below program two compare two Array list, But I don't want to miss the condition when both array list are same in size but content different values.Also is below code can be minimize.

ArrayList<String> firstList = new ArrayList<String> ( Arrays.asList("Cake", "pizza", "pasta") );
ArrayList<String> secondList = new ArrayList<String> ( Arrays.asList("Chocolate", "fruits", "pancake"));

if (!firstList.equals(secondList)) {
    if (firstList.size() > secondList.size()) {
        firstList.removeAll(secondList);
        SOP("Differance" + firstList+ "---------Total Number of Group mismatch----------"+ firstList.size());
    } else if (firstList.size() < secondList.size()) {
        secondList.removeAll(firstList);
        SOP("Differance" + secondList+ "---------Total Number of Group mismatch----------" + secondList.size());
    }
} else {
    SOP("Both are same");
}

Upvotes: 0

Views: 306

Answers (1)

Amit Kumar Lal
Amit Kumar Lal

Reputation: 5789

If u want to use a Third party utility u can directly use

System.out.println(CollectionUtils.disjunction(firstList, secondList));

To minimize simple use a single third list like below

public static void main(String[] args) {
        ArrayList<String> firstList = new ArrayList<String> ( Arrays.asList("Cake", "pizza", "pasta", "fruits") );
        ArrayList<String> secondList = new ArrayList<String> ( Arrays.asList("Chocolate", "fruits", "pancake"));         
        List<String> result = new ArrayList<String>();
        add(secondList, result);
        add(firstList, result);
        System.out.println(result);
    }

    public static void add(ArrayList<String> list, List<String> result) {
        for (String string : list) {
            if(result.contains(string)) {
                result.remove(string);
            }else {
                result.add(string);
            }
        }
    }

or if u are okay with modifying ur List (any one ) you can iterate one list and check teh data in another list

for (String string : firstList) {
            if(secondList.contains(string)) {
                secondList.remove(string);
            }else {
                secondList.add(string);
            }
        }
        System.out.println(secondList);

Upvotes: 1

Related Questions