Pick Prime Numbers from the ArrayList


 

Pick Prime Numbers from the ArrayList

In this section you will learn how to find the prime and non prime numbers separately from the arraylist.

In this section you will learn how to find the prime and non prime numbers separately from the arraylist.

Pick Prime Numbers from the ArrayList

Programmers mostly used ArrayList instead of Arrays as it fast and easy to use. Moreover, it has methods for inserting, deleting, and searching. It automatically expands on adding the data. It can be traversed using a foreach loop, iterators, or indexes. Here we have stored some integer values in the arraylist and from the arraylist we have to find the prime and non prime numbers separately.

Here is the code:

import java.util.*;

class PickNumbersFromList {
	static boolean isPrime(int number) {
		boolean isPrime = false;
		int i = (int) Math.ceil(Math.sqrt(number));
		while (i > 1) {
			if ((number != i) && (number % i == 0)) {
				isPrime = false;
				break;
			} else if (!isPrime)
				isPrime = true;
			--i;
		}
		return isPrime;
	}

	public static void main(String[] args) {
		ArrayList list = new ArrayList();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);
		list.add(6);
		list.add(7);
		list.add(8);
		list.add(9);
		list.add(10);
		Integer array[] = new Integer[list.size()];
		array = list.toArray(array);
		System.out.println("Prime Numbers are: ");
		for (int i = 0; i < array.length; i++) {
			if (isPrime(array[i])) {
				System.out.println(array[i]);
			}
		}
		System.out.println("Non Prime Numbers are: ");
		for (int i = 0; i < array.length; i++) {
			if (!isPrime(array[i])) {
				System.out.println(array[i]);
			}
		}
	}
}

Output:

Prime Numbers are:
2
3
5
7
Non Prime Numbers are:
1
4
6
8
10

Ads