1

I have two arraylist that has some elements I am comparing the elements of both arraylists and trying to extract the elements in third arraylist that are not common in both lists.

This is what I have done so far:

public class Details
{
   public static void main(String [] args)
    {

      ArrayList<String> al1= new ArrayList<String>();
      al1.add("hi");
      al1.add("How are you");
      al1.add("Good Morning");
      al1.add("bye");
      al1.add("Good night");

      ArrayList<String> al2= new ArrayList<String>();
      al2.add("Howdy");
      al2.add("Good Evening");
      al2.add("bye");
      al2.add("Good night");

      //Storing the comparison output in ArrayList<String>
      ArrayList<String> al3= new ArrayList<String>();
      for (String temp : al1)
          al3.add(al2.contains(temp) ? "Yes" : "No");
      System.out.println(al3);

  }
}

OUTPUT

[No, No, No, Yes, Yes]

I don't want output in yes or no form I want elements in new array list that are no common in both lists.

Someone please let me know how can I achieve desired result. Any help would be appreciated.

THANKS

1 Answer 1

2

First, please program to the List interface (instead of the ArrayList concrete type). You can also use Arrays.asList to shorten your initialization. I would then stream() each List - you want fo filter the stream for elements not contained in the other List and then add them to your third List. Something like,

List<String> al1 = Arrays.asList("hi", "How are you", "Good Morning", "bye", "Good night");
List<String> al2 = Arrays.asList("Howdy", "Good Evening", "bye", "Good night");
List<String> al3 = al1.stream().filter(s -> !al2.contains(s)).collect(Collectors.toList());
al3.addAll(al2.stream().filter(s -> !al1.contains(s)).collect(Collectors.toList()));
System.out.println(al3);

Which outputs

[hi, How are you, Good Morning, Howdy, Good Evening]

or, without streams (so you can better understand the algorithm),

List<String> al3 = new ArrayList<>();
for (String s : al1) {
    if (!al2.contains(s)) {
        al3.add(s);
    }
}
for (String s : al2) {
    if (!al1.contains(s)) {
        al3.add(s);
    }
}
System.out.println(al3);
Sign up to request clarification or add additional context in comments.

Comments

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.