Finding Common values in Arraylist Java Example

(Last Updated On: August 11, 2016)

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:

God
.Net
PHP
Java

List 2 contains:

C
Java
C++
.Net

Expected Values:

Common values are :::Java
Common values are :::.Net

Java Program to Find Common values in Arraylist:

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);
		}
	}
}

Output:

Common values are :::Java
Common values are :::.Net

Recommended Java Books:

2,307 total views, 22 views today

Leave a Reply

Your email address will not be published. Required fields are marked *