0% found this document useful (0 votes)
2 views47 pages

Java Array and Collection Processing

The document provides an overview of Java arrays, detailing their characteristics, types, and usage, including one-dimensional and multi-dimensional arrays. It explains how to declare, initialize, access, and manipulate arrays, as well as the Java Arrays class and its methods. Additionally, it introduces vectors, highlighting their dynamic nature and synchronization features compared to ArrayLists.

Uploaded by

westgodson66
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views47 pages

Java Array and Collection Processing

The document provides an overview of Java arrays, detailing their characteristics, types, and usage, including one-dimensional and multi-dimensional arrays. It explains how to declare, initialize, access, and manipulate arrays, as well as the Java Arrays class and its methods. Additionally, it introduces vectors, highlighting their dynamic nature and synchronization features compared to ArrayLists.

Uploaded by

westgodson66
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 47

CHAPTER ONE

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.

Arrays are used to store multiple values in a single variable, instead of


declaring separate variables for each value.

Arrays are of two types.

1 One Dimensional Array

2. Mutt- dimensional Array

A one-dimensional array in Java (and in programming in general) is the


simplest form of an array. It's like a single row or column of data. Think of it
as a linear sequence of elements, all of the same data type.
How to Declare and Initialize One Dimensional Arrays
To declare One Dimensional array, define the variable type with square
brackets:

String[] cars;

We have now declared a variable that holds an array of strings.

To insert values to it, you can place the values in a comma-separated list,
inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

String[] names = {"Alice", "Bob", "Charlie"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

You can also declare and initialize in different lines.

Declare an array of integers called 'numbers' with a size of 5

int[] numbers = new int[5];

Initialize the array elements

numbers[0] = 10;

numbers[1] = 20;

numbers[2] = 30;

numbers[3] = 40;

numbers[4] = 50;

Accessing the Elements of an Array


You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:


Example

public class Main

public static void main(String[] args)

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

Why Use Arrays?


1. Organized Storage: Arrays offer a structured way to store and
manage collections of related data efficiently.
2. Efficient Access: You can quickly retrieve any element in an array
using its index.
3. Code Readability: Arrays enhance the readability and maintainability
of your code by grouping related data together.

Example: Java program to Calculate the Sum of Array Elements

public class Main

public static void main(String[] args)

int[] scores = {85, 92, 78, 95, 88};

int sum = 0;

for (int i = 0; i < scores.length; i++)

{
sum += scores[i];

System.out.println("Total score: " + sum);

Changing an Array Element


To change the value of a specific element, refer to the index number:

Example

cars[0] = "Opel";

Example

public class Main

public static void main(String[] args)

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

System.out.println(cars[0]);

// Now outputs Opel instead of Volvo

Array Length
To find out how many elements an array has, use the length property:

Example

public class Main

{
public static void main(String[] args)

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length);

// Outputs 4

Exercise

How can you declare an array of strings?

a) string[] myText;
b) String[] myText;
c) str[] myText;
d) string = myText;

Arrays and Loops


Looping Through an Array

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.

The following example outputs all elements in the cars array:

Example

public class Main

public static void main(String[] args)

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++)

{
System.out.println(cars[i]);

Loop Through an Array with For-Each


There is also a "for-each" loop, which is used exclusively to loop through
elements in arrays:

Syntax

for (type variable : arrayname)

Statement(s);

The following example outputs all elements in the cars array, using a "for-
each" loop:

Example

public class Main

public static void main(String[] args)

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (String i : cars)

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

What is the output of the following code?

String[] cars = {"Volvo", "BMW", "Ford"};


for (int i = 0; i < cars.length; i++)

{
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

public static void main(String[] args)

// An array storing different ages

int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;

// Get the length of the array

int length = ages.length;

// Loop through the elements of the array

for (int age : ages)

sum += age;

// Calculate the average by dividing the sum by the length

avg = sum / length;

// Print the average

System.out.println("The average age is: " + avg);

And in this example, we create a program that finds the lowest age among
different ages:

Example

public class Main

public static void main(String[] args)

{
// An array storing different ages

int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

// Get the length of the array

int length = ages.length;

// Create a 'lowest age' variable and assign the first array element of ages
to it

int lowestAge = ages[0];

// Loop through the elements of the ages array to find the lowest age

for (int age : ages)

// Check if the current age is smaller than the current 'lowest age'

if (lowestAge > age)

// If the smaller age is found, update 'lowest age' with that element

lowestAge = age;

// Output the value of the lowest age

System.out.println("The lowest age in the array is: " + lowestAge);

How To Sort an Array


You can use the sort() method, found in in java.util.Arrays, to sort an
array:

Example

import java.util.Arrays;
public class Main

public static void main(String[] args)

String[] cars = {"Volvo", "BMW", "Tesla", "Ford", "Fiat", "Mazda", "Audi"};

Arrays.sort(cars);

for (String i : 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

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

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

public static void main(String[] args)

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };


System.out.println(myNumbers[1][2]);

Remember that: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.

Changing Element Values in Array


You can also change the value of an element:

Example

public class Main

public static void main(String[] args)

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers[1][2] = 9; System.out.println(myNumbers[1][2]); // Outputs 9


instead of 7

Looping Through a Multi-Dimensional Array


You can also use a for loop inside another for loop to get the elements of a
two-dimensional array (we still have to point to the two indexes):

Example
public class Main

public static void main(String[] args)

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i)

for(int j = 0; j < myNumbers[i].length; ++j)

{ System.out.println(myNumbers[i][j]);

Or you could just use a for-each loop, which is considered easier to read and
write:

Example

public class Main

public static void main(String[] args)

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int[] row : myNumbers)

for (int i : row)

System.out.println(i);
}

Exercise

What is a multidimensional array?

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

Java Arrays Class


The Java Arrays class (found in java.util), has methods that allow you to
manipulate arrays.

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

Arrays in Java are objects.

Accessing an element outside the bounds of an array will lead to an


ArrayIndexOutOfBoundsException.

Array as pointers in Java


In Java, when you pass array parameters to methods, they are passed by
reference. This means that any modifications made to the array within the
method will be reflected in the original array outside of that method. It's
worth noting that while Java doesn't use pointers in the same way as C or C+
+, it does utilize references, which can be considered somewhat similar.

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.

Simple Java Program Using Array Methods

public class ArrayPointerExample

{
// Method to print the elements of the array

public static void printArray(int[] array)

System.out.print("Array elements: ");

for (int element : array)

System.out.print(element + " ");

System.out.println();

// Method to modify the elements of the array (squares elements)

public static void squareArray(int[] array)

for (int i = 0; i < array.length; i++)

array[i] = array[i] * array[i]; // Square the element

// Method to fill the array with values

public static void fillArray(int[] array, int value) {

for (int i = 0; i < array.length; i++)

array[i] = value; // Fill the array with a specific value

public static void main(String[] args)

{
// Create an array

int[] myArray = new int[5];

// Fill the array with a specified value

fillArray(myArray, 2);

printArray(myArray); // Output: Array elements: 2 2 2 2 2

// Square the elements of the array

squareArray(myArray);

printArray(myArray); // Output: Array elements: 4 4 4 4 4

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.

3. fillArray: This method takes an `int[]` array and a value as parameters. It


fills the entire array with the specified value, showcasing another way to
manipulate the array.

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.

Running the Program


When you execute this program, the output will be:

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.

In Java, the Vector class, is found in the java.util.Vector package, it serves


as a dynamic array. While it shares similarities with ArrayList, there are
notable differences, particularly regarding synchronization.
Features of Vector in Java
1. Implements List Interface – Vector is part of the Java Collections
Framework as it implements the List interface.

2. Synchronized – Unlike ArrayList, Vector is synchronized, which ensures


thread safety but can result in slightly slower performance.

3. Resizable – It can dynamically expand, doubling its size when it


surpasses its current capacity.

4. Allows Duplicates – Similar to ArrayList, Vector permits duplicate


elements.

5. Maintains Insertion Order – The elements are stored in the sequence


they were added.

Declaration and Initialization


Vector<Type> variableName = new Vector<>();

Adding elements
vector.add(Value);

vector.add("String");

vector.add(variable);

Accessing elements
vector.get(index);

Iterating over Vector


for (Type newName : variableName)

System.out.println(newName);
}

Example
import java.util.Vector;

public class VectorExample

public static void main(String[] args)

// Creating a Vector of Strings

Vector<String> vector = new Vector<>();

// Adding elements

vector.add("Apple");

vector.add("Banana");

vector.add("Cherry");

// Accessing elements System.out.println("First element: " +


vector.get(0));

// Iterating over Vector

for (String fruit : vector)

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;

public class VectorAverage

public static void main(String[] args)

// Create a Vector to store numbers

Vector<Integer> numbers = new Vector<>();

// Add eight numbers to the 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);

// Calculate the sum of the numbers

int sum = 0;
for (int num : numbers)

sum += num;

// Calculate the average

double average = sum / (double) numbers.size();

// Display the average

System.out.println("The average of the numbers is: " + average);

Explanation:
1. Create a Vector<Integer> to store eight numbers.

2. Add numbers to the vector using the .add() method.

3. Calculate the sum of all elements using a for-each loop.

4. Compute the average by dividing the sum by the size of the vector.

5. Print the average to the console.

Output:

The average of the numbers is: 45.0

Why Use Vector?


Opt for Vector when you require thread safety.

If thread safety isn't a concern, ArrayList is a better choice for performance.


Would you like a comparison with ArrayList or an example of multi-threading
with Vector?

Multiple Inputs Box


In Java, we can utilize JOptionPane (part of javax.swing) to create several
input boxes for gathering user inputs. These inputs can then be stored in a
Vector for further processing.

Example Program: Using Multiple Input Boxes with a Vector

import javax.swing.*;

import java.util.Vector;

public class MultiInputVector

public static void main(String[] args)

// Create a Vector to store strings

Vector<String> stringVector = new Vector<>();

// Ask the user for the number of inputs

String inputCountStr = JOptionPane.showInputDialog("How many strings


do you want to enter?");

int inputCount = Integer.parseInt(inputCountStr);

// Loop to take multiple inputs

for (int i = 0; i < inputCount; i++)

String input = JOptionPane.showInputDialog("Enter string " + (i + 1)


+ ":");
stringVector.add(input);

// Display the collected strings

String message = "You entered:\n" + String.join("\n", stringVector);

JOptionPane.showMessageDialog(null, message);

Explanation:
1. Vector Initialization:

A Vector<String> is created to hold the user input strings.

2. Getting Number of Inputs:

The user is prompted to specify how many strings they wish to input using
JOptionPane.showInputDialog().

The input is then converted from String to int.

3. Looping for Multiple Inputs:

A for loop is employed to gather multiple inputs via


JOptionPane.showInputDialog().

Each entered string is added to the Vector.

4. Displaying Stored Strings:

The collected strings are shown using JOptionPane.showMessageDialog().

String.join("\n", stringVector) is used to format the output neatly.

Sample Interaction

Step 1: Input Count Prompt


[Input Box] "How many strings do you want to enter?"

User enters: 3

Step 2: String Inputs

[Input Box] "Enter string 1:"

User enters: "Apple"

[Input Box] "Enter string 2:"

User enters: "Banana"

[Input Box] "Enter string 3:"

User enters: "Cherry"

Advantages of Using Vectors


Dynamic Sizing: You don't have to set a fixed size for the array.

Thread-Safety: Vectors are synchronized, ensuring safety in multi-threaded


environments.

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()).

Sort Strings: Implement Collections.sort(stringVector) to organize the


strings before displaying.

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;

public class MultiInputIntVector

public static void main(String[] args)

// Create a Vector to store integers

Vector<Integer> intVector = new Vector<>();

// Ask the user for the number of inputs

String inputCountStr = JOptionPane.showInputDialog("How many


numbers do you want to enter?");

int inputCount = Integer.parseInt(inputCountStr); // Convert input to an


integer

// Loop to take multiple integer inputs

for (int i = 0; i < inputCount; i++)

String inputStr = JOptionPane.showInputDialog("Enter number " + (i


+ 1) + ":");

try

int number = Integer.parseInt(inputStr); // Convert string input to


integer

intVector.add(number); // Add to Vector

catch (NumberFormatException e)

{
JOptionPane.showMessageDialog(null, "Invalid input! Please enter
a valid integer.");

i--; // Decrement to reattempt input

// Display the collected numbers

String message = "You entered: " + intVector.toString();

JOptionPane.showMessageDialog(null, message);

Explanation:
1. Vector Initialization:

A Vector<Integer> is created to store integers.

2. Getting Number of Inputs:

The user is asked how many numbers they want to enter using
JOptionPane.showInputDialog().

The input is converted from String to int.

3. Looping for Multiple Inputs:

A for loop collects integer inputs.

Integer.parseInt() converts string input to an integer.

Input is added to the Vector<Integer>.

4. Input Validation:

If the user enters a non-integer, an error message appears, and the loop
retries input.

5. Displaying Stored Numbers:


The collected numbers are displayed in a message box using
JOptionPane.showMessageDialog().

Sample Interaction
Step 1: Input Count Prompt

[Input Box] "How many numbers do you want to enter?" User enters: 3

Step 2: Number Inputs

[Input Box] "Enter number 1:" User enters: 10

[Input Box] "Enter number 2:" User enters: 25

[Input Box] "Enter number 3:" User enters: 50

Step 3: Display Collected Numbers [Message Box]

You entered: [10, 25, 50]

Enhancements (Optional)

Sorting Numbers: Use Collections.sort(intVector) before displaying.

Sum and Average Calculation: Compute and display sum/average of the


numbers.

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

We're going to implement Stack using array in this textbook.

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 − push an element at the top of the stack.


 Pop − pop an element from the top of the stack.

There is few more operations supported by stack which are following.

 Peek − get the top element of the stack.


 isFull − check if stack is full.
 isEmpty − check if stack is empty.

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

public void push(int data)

if(!isFull())

// increment top by 1 and insert data

intArray[++top] = data;

Else

System.out.println("Cannot add data. Stack is full.");

}
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.

// Program to pop item from the top of the stack

public int pop()

// retrieve data and decrement the top by 1

return intArray[top--];

Stack Implementation
Stack.java

public class Stack


{

private int size; // size of the stack

private int[] intArray; // stack storage

private int top; // top of the stack

// Constructor

public Stack(int size)

this.size = size;

intArray = new int[size]; //initialize array

top = -1; //stack is initially empty

// Operation : Push

// push item on the top of the stack

public void push(int data)

if(!isFull())

// increment top by 1 and insert data

intArray[++top] = data;

Else

{ System.out.println("Cannot add data. Stack is full.");

// Operation : Pop
// pop item from the top of the stack

public int pop()

//retrieve data and decrement the top by 1

return intArray[top--];

// Operation : Peek

// view the data at top of the stack

public int peek()

//retrieve data from the top

return intArray[top];

// Operation : isFull

// return true if stack is full

public boolean isFull()

return (top == size-1);

// Operation : isEmpty

// return true if stack is empty

public boolean isEmpty()

return (top == -1);

}
}

Demo Program

StackDemo.java

public class StackDemo

public static void main (String[] args)

// make a new stack

Stack stack = new Stack(10);

// push items on to the stack

stack.push(3);

stack.push(5);

stack.push(9);

stack.push(1);

stack.push(12);

stack.push(15);

System.out.println("Element at top of the stack: " + stack.peek());

System.out.println("Elements: ");

// print stack data

while(!stack.isEmpty())

int data = stack.pop();

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 −

Element at top of the stack: 15

Elements:

15

12

Stack full: false

Stack empty: true

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.

 Peek − get the element at front of the queue.


 isFull − check if queue is full.
 isEmpty − check if queue is empty.

Insert / Enqueue Operation


Whenever an element is inserted into queue, queue increments the rear
index for later use and stores that element at the rear end of the storage. If
rear end reaches to the last index and it is wrapped to the bottom location.
Such an arrangement is called wrap around and such queue is circular
queue. This method is also termed as enqueue operation.

public void insert(int data)

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.

public int remove()

int data = intArray[front++];

if(front == MAX)

front = 0;

itemCount--;

return data;

}
Queue Implementation
Queue.java

public class Queue

private final int MAX;

private int[] intArray;

private int front;

private int rear;

private int itemCount;

public Queue(int size)

MAX = size;

intArray = new int[MAX];

front = 0;

rear = -1;

itemCount = 0;

public void insert(int data)

if(!isFull()){

if(rear == MAX-1)

rear = -1;

}
intArray[++rear] = data;

itemCount++;

public int remove()

int data = intArray[front++];

if(front == MAX)

front = 0;

itemCount--;

return data;

public int peek()

return intArray[front];

public boolean isEmpty()

return itemCount == 0;

public boolean isFull()

{
return itemCount == MAX;

public int size()

return itemCount;

Demo Program

QueueDemo.java

public class QueueDemo

public static void main(String[] args)

Queue queue = new Queue(6);

//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!");

//remove one item

int num = queue.remove(); System.out.println("Element removed:


"+num);

// 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

//As queue is full, elements will not be inserted.

queue.insert(17);

queue.insert(18);

// ----------------------

// index : 0 1 2 3 4 5

// ----------------------

// queue :16 5 9 1 12 15

System.out.println("Element at front: "+queue.peek());

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

System.out.print(n +" ");


}

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

CHAPTER THREE COLLECTION PROCESSING IN


JAVA

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

Java provides several ways to process collections:

(a) Using Iterators

Iterators are used to traverse elements in a collection.

Example: Using Iterator

import java.util.*;

public class IteratorExample {

public static void main(String[] args)

List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob",


"Charlie"));

Iterator<String> iterator = names.iterator();

while (iterator.hasNext())

{ System.out.println(iterator.next());

Best for: Iterating elements one by one with flexibility.

(b) Using Enhanced For-Loop (for-each)

A simple way to iterate through collections.

Example: Using for-each Loop

List<Integer> numbers = Arrays.asList(10, 20, 30, 40);

for (int num : numbers)

{
System.out.println(num);

Best for: Readable and concise iteration.

(c) Using Streams (Functional Programming Approach - Java 8+)

Java 8 introduced the Streams API for efficient collection processing.

Example: Using Streams

List<Integer> numbers = Arrays.asList(10, 20, 30, 40);

numbers.stream().forEach(System.out::println);

Best for: Parallel processing and functional-style operations.

2. Common Operations on Collections

Java provides multiple operations to process collections:

(D) Example: Processing with Streams

import java.util.*;

import java.util.stream.Collectors;

public class StreamExample

public static void main(String[] args)

List<Integer> numbers = Arrays.asList(5, 10, 15, 20, 25);

// Filter numbers > 10 and double them

List<Integer> result = numbers.stream()


.filter(n -> n > 10)

.map(n -> n * 2)

.collect(Collectors.toList());

System.out.println(result); // Output: [30, 40, 50]

Advantages of Streams: Concise, readable, and supports parallel


processing.

3. Collection Processing with Parallel Streams

For large data, parallel streams process collections concurrently for better
performance.

Example: Parallel Processing

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

numbers.parallelStream().forEach(System.out::println);

Best for: Performance improvement in large datasets.

Conclusion

Collection Processing in Java provides multiple methods:

Iterators for controlled traversal.

For-each loops for easy iteration.

Streams API for efficient functional-style processing.

Parallel Streams for enhanced performance.


Each method is useful depending on the scenario and data size. Would you
like an example for a specific use case?

You might also like