Java Arrays and Collections Framework
Programs
1 Arrays in Java
Arrays are fixed-size, contiguous data structures that store elements of the
same type. They are indexed starting from 0 and provide fast access (O(1))
but lack dynamic resizing capabilities.
1.1 10 Basic Array Programs
Below are 10 Java programs demonstrating common array operations.
1. Print Array: Initializes and prints an array.
1 public class ArrayProgram1 {
2 public static void main(String[] args) {
3 int[] arr = {1, 2, 3, 4, 5};
4 for (int i = 0; i < arr.length; i++) {
5 System.out.print(arr[i] + " ");
6 }
7 }
8 }
Output: 1 2 3 4 5
2. Sum of Array Elements: Calculates the sum of all elements.
1 public class ArrayProgram2 {
2 public static void main(String[] args) {
3 int[] arr = {10, 20, 30, 40, 50};
4 int sum = 0;
5 for (int num : arr) {
6 sum += num;
7 }
8 System.out.println("Sum: " + sum);
9 }
10 }
Output: Sum: 150
3. Find Maximum Element: Finds the largest element in an array.
1
1 public class ArrayProgram3 {
2 public static void main(String[] args) {
3 int[] arr = {5, 2, 9, 1, 7};
4 int max = arr[0];
5 for (int i = 1; i < arr.length; i++) {
6 if (arr[i] > max) {
7 max = arr[i];
8 }
9 }
10 System.out.println("Max: " + max);
11 }
12 }
Output: Max: 9
4. Reverse Array: Prints the array in reverse order.
1 public class ArrayProgram4 {
2 public static void main(String[] args) {
3 int[] arr = {1, 2, 3, 4, 5};
4 for (int i = arr.length - 1; i >= 0; i--) {
5 System.out.print(arr[i] + " ");
6 }
7 }
8 }
Output: 5 4 3 2 1
5. Check if Element Exists: Checks if a given element exists in the
array.
1 public class ArrayProgram5 {
2 public static void main(String[] args) {
3 int[] arr = {10, 20, 30, 40, 50};
4 int target = 30;
5 boolean found = false;
6 for (int num : arr) {
7 if (num == target) {
8 found = true;
9 break;
10 }
11 }
12 System.out.println("Element " + target + " found: " +
found);
13 }
14 }
Output: Element 30 found: true
6. Copy Array: Copies elements from one array to another.
1 public class ArrayProgram6 {
2
2 public static void main(String[] args) {
3 int[] arr = {1, 2, 3, 4, 5};
4 int[] copy = new int[arr.length];
5 for (int i = 0; i < arr.length; i++) {
6 copy[i] = arr[i];
7 }
8 System.out.print("Copied Array: ");
9 for (int num : copy) {
10 System.out.print(num + " ");
11 }
12 }
13 }
Output: Copied Array: 1 2 3 4 5
7. Sort Array (Bubble Sort): Sorts an array using bubble sort.
1 public class ArrayProgram7 {
2 public static void main(String[] args) {
3 int[] arr = {64, 34, 25, 12, 22};
4 for (int i = 0; i < arr.length - 1; i++) {
5 for (int j = 0; j < arr.length - i - 1; j++) {
6 if (arr[j] > arr[j + 1]) {
7 int temp = arr[j];
8 arr[j] = arr[j + 1];
9 arr[j + 1] = temp;
10 }
11 }
12 }
13 System.out.print("Sorted Array: ");
14 for (int num : arr) {
15 System.out.print(num + " ");
16 }
17 }
18 }
Output: Sorted Array: 12 22 25 34 64
8. Find Array Length: Displays the length of an array.
1 public class ArrayProgram8 {
2 public static void main(String[] args) {
3 int[] arr = {1, 2, 3, 4, 5};
4 System.out.println("Array Length: " + arr.length);
5 }
6 }
Output: Array Length: 5
9. Initialize 2D Array: Initializes and prints a 2D array.
1 public class ArrayProgram9 {
2 public static void main(String[] args) {
3
3 int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
4 for (int i = 0; i < arr.length; i++) {
5 for (int j = 0; j < arr[i].length; j++) {
6 System.out.print(arr[i][j] + " ");
7 }
8 System.out.println();
9 }
10 }
11 }
Output:
1 2 3
4 5 6
7 8 9
10. Average of Array Elements: Calculates the average of array ele-
ments.
1 public class ArrayProgram10 {
2 public static void main(String[] args) {
3 int[] arr = {10, 20, 30, 40, 50};
4 double avg = 0;
5 for (int num : arr) {
6 avg += num;
7 }
8 avg /= arr.length;
9 System.out.println("Average: " + avg);
10 }
11 }
Output: Average: 30.0
2 Java Collections Framework
The Java Collections Framework (JCF) provides a set of classes and inter-
faces in the java.util package for managing dynamic collections. It in-
cludes interfaces like List, Set, and Map, with implementations such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap.
2.1 10 Basic Collections Programs
Below are 10 Java programs demonstrating JCF operations, including iter-
ators, enhanced for loops, and sorting with Comparable and Comparator.
1. ArrayList Operations: Adds and removes elements from an ArrayList.
1 import java.util.ArrayList; can show duplicated
2
3 public class CollectionProgram1 {
4 public static void main(String[] args) {
4
5 ArrayList<Integer> list = new ArrayList<>();
6 list.add(10);
7 list.add(20);
8 list.add(30);
9 System.out.println("ArrayList: " + list);
10 list.remove(1);
11 System.out.println("After removing index 1: " + list);
12 }
13 }
Output:
ArrayList: [10, 20, 30]
After removing index 1: [10, 30]
2. LinkedList Operations: Adds elements to a LinkedList and inserts
at the start. can show duplicates
1 import java.util.LinkedList;
2
3 public class CollectionProgram2 {
4 public static void main(String[] args) {
5 LinkedList<String> list = new LinkedList<>();
6 list.add("Apple");
7 list.add("Banana");
8 list.add("Orange");
9 System.out.println("LinkedList: " + list);
10 list.addFirst("Mango");
11 System.out.println("After adding Mango at start: " +
list);
12 }
13 }
Output:
LinkedList: [Apple, Banana, Orange]
After adding Mango at start: [Mango, Apple, Banana, Orange]
3. HashSet Operations: Adds elements to a HashSet, demonstrating no
duplicates. no duplicates ....
1 import java.util.HashSet;
2
3 public class CollectionProgram3 {
4 public static void main(String[] args) {
5 HashSet<String> set = new HashSet<>();
6 set.add("Dog");
7 set.add("Cat");
8 set.add("Dog");
9 System.out.println("HashSet: " + set);
5
10 System.out.println("Contains Cat: " +
set.contains("Cat"));
11 }
12 }
Output:
HashSet: [Dog, Cat]
Contains Cat: true
4. TreeSet Operations: Adds elements to a TreeSet, showing sorted
order. always sorted ... and no duplicates
1 import java.util.TreeSet;
2
3 public class CollectionProgram4 {
4 public static void main(String[] args) {
5 TreeSet<Integer> set = new TreeSet<>();
6 set.add(50);
7 set.add(20);
8 set.add(30);
9 System.out.println("TreeSet (sorted): " + set);
10 }
11 }
Output: TreeSet (sorted): [20, 30, 50]
5. HashMap Operations: Adds key-value pairs to a HashMap and re-
trieves a value. sorted by key ascending order and no
1 import java.util.HashMap; duplicates ...
2
3 public class CollectionProgram5 {
4 public static void main(String[] args) {
5 HashMap<Integer, String> map = new HashMap<>();
6 map.put(1, "Alice");
7 map.put(2, "Bob");
8 map.put(3, "Charlie");
9 System.out.println("HashMap: " + map);
10 System.out.println("Value for key 2: " + map.get(2));
11 }
12 }
Output:
HashMap: {1=Alice, 2=Bob, 3=Charlie}
Value for key 2: Bob
6. TreeMap Operations: Adds key-value pairs to a TreeMap, showing
sorted keys.
6
sorted by key descending order and no duplicates ...
1 import java.util.TreeMap;
2
3 public class CollectionProgram6 {
4 public static void main(String[] args) {
5 TreeMap<String, Integer> map = new TreeMap<>();
6 map.put("Zebra", 1);
7 map.put("Apple", 2);
8 map.put("Banana", 3);
9 System.out.println("TreeMap (sorted by keys): " + map);
10 }
11 }
Output: TreeMap (sorted by keys): Apple=2, Banana=3, Zebra=1
7. Iterator with ArrayList: Uses an iterator to traverse an ArrayList.
1 import java.util.ArrayList; common iterator
2 import java.util.Iterator; methods
3 1. hasNext() = returns
4 public class CollectionProgram7 { true if there are more
5 public static void main(String[] args) { elements
6 ArrayList<String> list = new ArrayList<>(); 2. next()= returns the
7 list.add("A"); next element
8 list.add("B"); 3. remove()= removes
9 list.add("C"); the last element
10 Iterator<String> iterator = list.iterator(); returned by next().
11 System.out.print("Using Iterator: ");
12 while (iterator.hasNext()) { no sorting
13 System.out.print(iterator.next() + " ");
14 }
15 }
16 }
Output: Using Iterator: A B C
8. Enhanced For Loop with HashSet: Uses an enhanced for loop to
traverse a HashSet.
1 import java.util.HashSet;
2
3 public class CollectionProgram8 {
4 public static void main(String[] args) {
5 HashSet<Integer> set = new HashSet<>();
6 set.add(1);
7 set.add(2);
8 set.add(3);
9 set.add(4);
10 System.out.print("Using Enhanced For Loop: ");
11 for (Integer num : set) {
12 System.out.print(num + " ");
13 }
14 }
7
15 }
Output: Using Enhanced For Loop: 1 2 3 4
9. Comparable Interface: Sorts objects using the Comparable inter-
face.
1 import java.util.TreeSet;
2
3 public class CollectionProgram9 {
4 static class Person implements Comparable<Person> {
5 String name;
6 int age;
7 Person(String name, int age) {
8 this.name = name;
9 this.age = age;
10 }
11 @Override
12 public int compareTo(Person other) {
13 return this.age - other.age;
14 }
15 @Override
16 public String toString() {
17 return name + "(" + age + ")";
18 }
19 }
20 public static void main(String[] args) {
21 TreeSet<Person> set = new TreeSet<>();
22 set.add(new Person("Alice", 25));
23 set.add(new Person("Bob", 20));
24 set.add(new Person("Charlie", 30));
25 System.out.println("TreeSet of Persons (sorted by age):
" + set);
26 }
27 }
Output: TreeSet of Persons (sorted by age): [Bob(20), Alice(25), Char-
lie(30)]
10. Comparator Interface: Sorts objects using a custom Comparator.
1 import java.util.ArrayList;
2 import java.util.Collections;
3 import java.util.Comparator;
4
5 public class CollectionProgram10 {
6 static class Person {
7 String name;
8 int age;
9 Person(String name, int age) {
10 this.name = name;
11 this.age = age;
12 }
8
13 @Override
14 public String toString() {
15 return name + "(" + age + ")";
16 }
17 }
18 public static void main(String[] args) {
19 ArrayList<Person> list = new ArrayList<>();
20 list.add(new Person("Alice", 25));
21 list.add(new Person("Bob", 20));
22 list.add(new Person("Charlie", 30));
23 Comparator<Person> nameComparator = (p1, p2) ->
p1.name.compareTo(p2.name);
24 Collections.sort(list, nameComparator);
25 System.out.println("ArrayList sorted by name: " + list);
26 }
27 }
Output: ArrayList sorted by name: [Alice(25), Bob(20), Charlie(30)]