Compare two object ArrayList in java

In this tutorial we will learn how to compare two ArrayList. We would be using contains[] method for comparing two elements of different ArrayList.

public boolean contains[Object o]
It returns true if the list contains the Object o else it returns false.

Example:

In this example we have two ArrayListal1 and al2 of String type. We have compared these ArrayLists using contains[] method and stored the comparison result in third ArrayList [al3 and al4].

package beginnersbook.com; import java.util.ArrayList; public class Details { public static void main[String [] args] { ArrayList al1= new ArrayList[]; al1.add["hi"]; al1.add["How are you"]; al1.add["Good Morning"]; al1.add["bye"]; al1.add["Good night"]; ArrayList al2= new ArrayList[]; al2.add["Howdy"]; al2.add["Good Evening"]; al2.add["bye"]; al2.add["Good night"]; //Storing the comparison output in ArrayList ArrayList al3= new ArrayList[]; for [String temp : al1] al3.add[al2.contains[temp] ? "Yes" : "No"]; System.out.println[al3]; //Storing the comparison output in ArrayList ArrayList al4= new ArrayList[]; for [String temp2 : al1] al4.add[al2.contains[temp2] ? 1 : 0]; System.out.println[al4]; } }

Output:

[No, No, No, Yes, Yes] [0, 0, 0, 1, 1]

What is the logic in above code?
If the first element of ArrayList al1 is present in al2 then ArrayList al3 would be having Yes and al4 would be having 1 However if the element is not present No would be stored in al3 and 0 would be in al4.

Video liên quan

Chủ Đề