Taking only String values from ArrayList

Scenario:
You are given with a arraylist with all datatype values. Eg: Integer and String values. But
you want to move only string values to another arraylist.

Solution you can think suddenly:
ArrayList can be declared to hold only string and using addAll method we can move.
Eg:
ArrayList arStr = new ArrayList();
arStr.addAll(“given_arrayList”);

But the above one does not throw any error as well which will move all the values(String and Integer) to another list.
If you try to move using add method which will throw casting exception.

So How can we do ?

package in.javadomain;

import java.util.ArrayList;

public class StringOnlyAL{

	public static void main(String[] args) {
		ArrayList alAll = new ArrayList();
		alAll.add("Java");
		alAll.add("DotNet");
		alAll.add(100);
		alAll.add("PHP");
		alAll.add(410);

		ArrayList<String> alStr = new ArrayList<String>();
		for (Object alAllval : alAll) {
			if (alAllval instanceof String) {
				alStr.add((String) alAllval);
			}
		}

		for (Object alStrVal : alStr) {
			System.out.println(alStrVal);
		}
	}

}

Output:

Java
DotNet
PHP

In the above we are checking the data type using instance of and based on that we are moving the string values alone to another arraylist using add method. If you have anyother solution for the same problem, kindly post in the comment area.

Recommended Books:

310 total views, 1 views today

Leave a Reply

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