Finding Common values in Arraylist:
Two arraylists are iterated one inside another for loop and common values are inserted in the common arraylist.
Input:
List 1 contains:
[plain gutter=”false”]God
.Net
PHP
Java
[/plain]
List 2 contains:
[plain gutter=”false”]C
Java
C++
.Net
[/plain]
Expected Values:
[plain gutter=”false”]
Common values are :::Java
Common values are :::.Net
[/plain]
Java Program to Find Common values in Arraylist:
[java gutter=”false”]
import java.util.ArrayList;
import java.util.List;
public class FindCommonValue {
public static void main(String[] args) {
List<String> myList1 = new ArrayList<String>();
myList1.add("God");
myList1.add(".Net");
myList1.add("PHP");
myList1.add("Java");
List<String> myList2 = new ArrayList<String>();
myList2.add("C");
myList2.add("Java");
myList2.add("C++");
myList2.add(".Net");
List<String> commonList = new ArrayList<String>();
for (String list2Val : myList2) {
for (String list1Val : myList1) {
if (list2Val.equalsIgnoreCase(list1Val)) {
commonList.add(list2Val);
}
}
}
for (String string : commonList) {
System.out.println("Common values are :::" + string);
}
}
}
[/java]
Output:
[plain gutter=”false”]
Common values are :::Java
Common values are :::.Net
[/plain]
Recommended Java Books: