Java Array and Collection Processing
Java Array and Collection Processing
JAVA ARRAYS
Arrays
In Java, an array is a basic data structure that enables you to store multiple
values of the same type in a continuous block of memory. Here’s a closer
look at what this entails and its advantages:
Characteristics
1. Homogeneous Elements: All elements in a single array must be of
the same data type (e.g., all integers, all strings, etc.).
2. Fixed Size: Once an array is created, its size cannot be changed. You
cannot dynamically add or remove elements.
3. Contiguous Memory: The elements of an array are stored in
consecutive memory locations, allowing for efficient access using their
index.
4. Zero-Based Indexing: The first element is at index 0, the second at
index 1, and so forth.
String[] cars;
To insert values to it, you can place the values in a comma-separated list,
inside curly braces:
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println(cars[0]);
Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.
int sum = 0;
{
sum += scores[i];
Example
cars[0] = "Opel";
Example
cars[0] = "Opel";
System.out.println(cars[0]);
Array Length
To find out how many elements an array has, use the length property:
Example
{
public static void main(String[] args)
System.out.println(cars.length);
// Outputs 4
Exercise
a) string[] myText;
b) String[] myText;
c) str[] myText;
d) string = myText;
You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.
Example
{
System.out.println(cars[i]);
Syntax
Statement(s);
The following example outputs all elements in the cars array, using a "for-
each" loop:
Example
System.out.println(i);
}
The example above can be read like this: for each String element (called i –
as in the index) in cars, print out the value of i.
If you compare the for loop and for-each loop, you will see that the for-
each method is easier to write, it does not require a counter (using the
length property), and it is more readable.
Exercise
{
System.out.println(cars[i]);
}
a) Volvo
BMW
Ford
b) 0
1
2
c) Volvo, BMW, Ford
d) Volvo,
BMW,
Ford
Real-Life Examples
To demonstrate a practical example of using arrays, let's create a program
that calculates the average of different ages:
Example
public class Main
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
sum += age;
And in this example, we create a program that finds the lowest age among
different ages:
Example
{
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
// Create a 'lowest age' variable and assign the first array element of ages
to it
// Loop through the elements of the ages array to find the lowest age
// Check if the current age is smaller than the current 'lowest age'
// If the smaller age is found, update 'lowest age' with that element
lowestAge = age;
Example
import java.util.Arrays;
public class Main
Arrays.sort(cars);
System.out.println(i);
Multi-Dimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular
form, like a table with rows and columns.
To create a two-dimensional array, add each array within its own set of curly
braces:
Example
Access Elements
To access the elements of the myNumbers array, specify two indexes: one for
the array, and one for the element inside that array. This example accesses
the third element (2) in the second array (1) of myNumbers:
Example
public class Main
Remember that: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Example
Example
public class Main
{ System.out.println(myNumbers[i][j]);
Or you could just use a for-each loop, which is considered easier to read and
write:
Example
System.out.println(i);
}
Exercise
a) Executed (every time) after the code block has been executed
b) An empty array
c) An array of arrays
d) Executed (one time) before the execution of the code block
Arrays Methods
A list of popular methods of the Arrays Class can be found in the table below:
Method Description
compare() Compares two arrays
copyOf() Creates a copy of an
array with a new length
deepEquals Compares two
() multidimensional arrays
to check whether they
are deeply equal to each
other
equals() Checks if two arays are
equal
fill() Fills an array with a
specified value
mismatch() Returns the index
position of the first
mismatch/conflict
between two arrays
sort() Sorts an array in
ascending order
Properties
Property Description
length Returns the length of an
array
The length property is a built-in Java property, and does not belong to the
Arrays class.
Notes
Below is an example of how to define methods in Java that accept arrays and
perform various manipulations on them. The program illustrates different
methods that take an array as a parameter and alter it in several ways.
{
// Method to print the elements of the array
System.out.println();
{
// Create an array
fillArray(myArray, 2);
squareArray(myArray);
Explanation:
1. printArray: This method takes an `int[]` array as a parameter and prints
its elements, demonstrating how to access and display array values.
2. squareArray: This method takes an `int[]` array as input and modifies its
contents by squaring each element. It demonstrates how to change the
values of an array that is passed to a method.
4. main method: The main method initializes an array of size 5, fills it with
the value `2`, prints the array, then modifies it by squaring each element
and prints the updated array again.
Array elements: 2 2 2 2 2
Array elements: 4 4 4 4 4
This illustrates how methods can be created to accept arrays and modify
them in Java, similar to how pointers to arrays are handled in other
programming languages like C/C++.
CHAPTER TWO
VECTOR, STACK, AND QUEUE
Vector
A vector is a mathematical construct defined as an object that can be added to
another object of the same type, or be multiplied by any real (or complex)
number resulting in another vector of the same type.
Vectors are kind of arrays or you can say vectors are dynamic arrays in
programming, which is used to store data/elements in contiguous storage
location.
Vectors are the same as dynamic arrays with the ability to resize itself
automatically when an element is inserted or deleted. Vector elements are
placed in contiguous storage so that they can be accessed and traversed
using iterators. In vectors, data is inserted at the end.
Adding elements
vector.add(Value);
vector.add("String");
vector.add(variable);
Accessing elements
vector.get(index);
System.out.println(newName);
}
Example
import java.util.Vector;
// Adding elements
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
System.out.println(fruit);
}
Example
Here's a Java program that uses a Vector to store eight numbers and
calculates their average:
import java.util.Vector;
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
numbers.add(60);
numbers.add(70);
numbers.add(80);
int sum = 0;
for (int num : numbers)
sum += num;
Explanation:
1. Create a Vector<Integer> to store eight numbers.
4. Compute the average by dividing the sum by the size of the vector.
Output:
import javax.swing.*;
import java.util.Vector;
JOptionPane.showMessageDialog(null, message);
Explanation:
1. Vector Initialization:
The user is prompted to specify how many strings they wish to input using
JOptionPane.showInputDialog().
Sample Interaction
User enters: 3
Built-in Methods: Functions like .add(), .get(), and .size() make data
management easier.
Enhancements (Optional)
Validate Inputs: Ensure inputs aren't empty by using if (input != null && !
input.trim().isEmpty()).
Search Feature: Enable users to look for a specific string within the vector.
Java Program to take Integer Inputs Using Multiple Input Boxes and Storing in
a Vector
This program uses JOptionPane to take multiple integer inputs from the user
and store them in a Vector<Integer>.
import javax.swing.*;
import java.util.Vector;
try
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Invalid input! Please enter
a valid integer.");
JOptionPane.showMessageDialog(null, message);
Explanation:
1. Vector Initialization:
The user is asked how many numbers they want to enter using
JOptionPane.showInputDialog().
4. Input Validation:
If the user enters a non-integer, an error message appears, and the loop
retries input.
Sample Interaction
Step 1: Input Count Prompt
[Input Box] "How many numbers do you want to enter?" User enters: 3
Enhancements (Optional)
Find Maximum and Minimum: Identify the highest and lowest number
entered.
Stack
Stack is kind of data structure which allows operations on data only at one
end. It allows access to the last inserted data only. Stack is also called LIFO
(Last In First Out) data structure and Push and Pop operations are related in
such a way that only last item pushed (added to stack) can be popped
(removed from the stack).
Stack Representation
Learn Java in-depth with real-world projects through our Java certification
course. Enroll and become a certified expert to boost your career.
Basic Operations
Following are two primary operations of a stack which are following.
Push Operation
Whenever an element is pushed into stack, stack stores that element at the
top of the storage and increments the top index for later use. If storage is full
then an error message is usually shown.
// Program to push item on the top of the stack
if(!isFull())
intArray[++top] = data;
Else
}
Pop Operation
Whenever an element is to be popped from stack, stack retrieves the
element from the top of the storage and decrements the top index for later
use.
return intArray[top--];
Stack Implementation
Stack.java
// Constructor
this.size = size;
// Operation : Push
if(!isFull())
intArray[++top] = data;
Else
// Operation : Pop
// pop item from the top of the stack
return intArray[top--];
// Operation : Peek
return intArray[top];
// Operation : isFull
// Operation : isEmpty
}
}
Demo Program
StackDemo.java
stack.push(3);
stack.push(5);
stack.push(9);
stack.push(1);
stack.push(12);
stack.push(15);
System.out.println("Elements: ");
while(!stack.isEmpty())
System.out.println(data);
} System.out.println("Stack full: " + stack.isFull());
System.out.println("Stack empty: " + stack.isEmpty());
If we compile and run the above program then it would produce following result −
Elements:
15
12
Queue
Queue is kind of data structure similar to stack with primary difference that
the first item inserted is the first item to be removed (FIFO - First In First Out)
where stack is based on LIFO, Last In First Out principal.
Queue Representation
Basic Operations
insert / enqueue − add an item to the rear of the queue.
remove / dequeue − remove an item from the front of the queue.
We're going to implement Queue using array in this article. There is few
more operations supported by queue which are following.
if(!isFull())
if(rear == MAX-1)
rear = -1;
intArray[++rear] = data;
itemCount++;
}
Remove / Dequeue Operation
Whenever an element is to be removed from queue, queue get the element using front index and
increments the front index. As a wrap around arrangement, if front index is more than array's
max index, it is set to 0.
if(front == MAX)
front = 0;
itemCount--;
return data;
}
Queue Implementation
Queue.java
MAX = size;
front = 0;
rear = -1;
itemCount = 0;
if(!isFull()){
if(rear == MAX-1)
rear = -1;
}
intArray[++rear] = data;
itemCount++;
if(front == MAX)
front = 0;
itemCount--;
return data;
return intArray[front];
return itemCount == 0;
{
return itemCount == MAX;
return itemCount;
Demo Program
QueueDemo.java
//insert 5 items
queue.insert(3);
queue.insert(5);
queue.insert(9);
queue.insert(1);
queue.insert(12);
// front : 0
// rear : 4
// ------------------
// index : 0 1 2 3 4
// ------------------
// queue : 3 5 9 1 12
queue.insert(15);
// front : 0
// rear : 5
// ---------------------
// index : 0 1 2 3 4 5
// ---------------------
// queue : 3 5 9 1 12 15
if(queue.isFull())
System.out.println("Queue is full!");
// front : 1
// rear : 5
// -------------------
// index : 1 2 3 4 5
// -------------------
// queue : 5 9 1 12 15
//insert more items
queue.insert(16);
// front : 1
// rear : -1
// ----------------------
// index : 0 1 2 3 4 5
// ----------------------
// queue :16 5 9 1 12 15
queue.insert(17);
queue.insert(18);
// ----------------------
// index : 0 1 2 3 4 5
// ----------------------
// queue :16 5 9 1 12 15
System.out.println("----------------------");
System.out.println("index : 5 4 3 2 1 0");
System.out.println("----------------------");
System.out.print("Queue: ");
while(!queue.isEmpty()){
int n = queue.remove();
If we compile and run the above program then it would produce following
result −
Queue is full!
Element removed: 3
Element at front: 5
----------------------
index : 5 4 3 2 1 0
----------------------
Queue: 5 9 1 12 15 16
Collection Processing
Collection Processing in Java refers to the various ways of managing,
manipulating, and performing operations on collections (like lists, sets, and
maps) efficiently. Java provides a rich API in the Java Collections Framework
(JCF) to process collections effectively.
1. Collection Processing Methods
import java.util.*;
while (iterator.hasNext())
{ System.out.println(iterator.next());
{
System.out.println(num);
numbers.stream().forEach(System.out::println);
import java.util.*;
import java.util.stream.Collectors;
.map(n -> n * 2)
.collect(Collectors.toList());
For large data, parallel streams process collections concurrently for better
performance.
numbers.parallelStream().forEach(System.out::println);
Conclusion