In this section, we are going to compare two array lists and display the different elements from both of them using Java Programming.
In this section, we are going to compare two array lists and display the different elements from both of them using Java Programming.In this section, we are going to compare two array lists and display the different elements from both of them. To show the different elements from the two list, we have created two array lists a1 and a2 and add some elements to both of them. Then we have created an object of HashSet class and add all the list elements to it. After that we have created a condition that if the list a1 does not contains the elements that are present in list a2, and vice versa then add those elements to another ArrayList list. Now this list contains all the elements that are not common to both the lists.
Here is the code:
import java.util.*; public class DisplayDifferentElement{ public static void main(String[]args){ ArrayList a1 = new ArrayList(); ArrayList a2 = new ArrayList(); a1.add("a"); a1.add("fdf"); a1.add("h"); a1.add("d"); a1.add("e"); a2.add("a"); a2.add("b"); a2.add("ch"); int array1Size = a1.size(); int array2Size = a2.size(); Set s = new HashSet(); s.addAll(a1); s.addAll(a2); ArrayList list = new ArrayList(); for(int i=0; i<a2.size(); i++) { if(!a1.contains(a2.get(i))) { list.add(a2.get(i)); } } for(int i=0; i<a1.size(); i++) { if(!a2.contains(a1.get(i))) { list.add(a1.get(i)); } } System.out.println("Elements which are different: "+list); System.out.println(""); for(int i = 0; i < list.size(); i++){ System.out.print((String)list.get(i)+" "); } } } |
Output:
b ch fdf h d e |