0

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");
}
3
  • Add an else to your inner if\else if. That will handle the case where they are the same size. Commented Aug 17, 2020 at 18:11
  • @JohnnyMopp, But How to print differance Commented Aug 17, 2020 at 19:20
  • How can I return the difference between two lists? Commented Aug 17, 2020 at 19:57

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks below work for me. System.out.println(CollectionUtils.disjunction(firstList, secondList

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.