Finding Common values in Arraylist Java Example

Finding Common values in Arraylist Java Example

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:

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:
[plain gutter=”false”]
Common values are :::Java
Common values are :::.Net
[/plain]

Recommended Java Books:

8,365 total views, 2 views today

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.