Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Solved Exercises – ArrayList in Java

Exercise 1: Filtering Even Numbers

  • Goal: Practice iterating through an ArrayList and conditional logic.
  • Task:
    1. Create an ArrayList that can store Integer objects.
    2. Add the numbers 1, 5, 10, 15, 20, 25 to the ArrayList.
    3. Create a new empty ArrayList called evenNumbers.
    4. Iterate through the first ArrayList. For each number, check if it’s even. If it is, add it to the evenNumbers ArrayList.
    5. Print both the original ArrayList and the evenNumbers ArrayList.

 

Solution

import java.util.ArrayList;

public class EvenNumberFilter {
    public static void main(String[] args) {
        // 1. Create an ArrayList that can store Integer objects.
        ArrayList numbers = new ArrayList<>();

        // 2. Add the numbers 1, 5, 10, 15, 20, 25 to the ArrayList.
        numbers.add(1);
        numbers.add(5);
        numbers.add(10);
        numbers.add(15);
        numbers.add(20);
        numbers.add(25);

        // 3. Create a new empty ArrayList called evenNumbers.
        ArrayList evenNumbers = new ArrayList<>();

        // 4. Iterate through the first ArrayList. For each number, check if it's even. If it is, add it to the evenNumbers ArrayList.
        for (int number : numbers) {
            if (number % 2 == 0) {
                evenNumbers.add(number);
            }
        }

        // 5. Print both the original ArrayList and the evenNumbers ArrayList.
        System.out.println("Original ArrayList: " + numbers);
        System.out.println("Even Numbers ArrayList: " + evenNumbers);
    }
}


 

Exercise 2: Combining and Removing Duplicates

  • Goal: Learn to combine ArrayLists and handle duplicate entries.
  • Task:
    1. Create two ArrayLists of String objects:
      • list1 with elements: “apple”, “banana”, “orange”, “apple”
      • list2 with elements: “banana”, “grape”, “kiwi”, “orange”
    2. Create a new ArrayList called combinedList.
    3. Add all elements from list1 to combinedList.
    4. Add all elements from list2 to combinedList.
    5. Create another new ArrayList called uniqueList.
    6. Iterate through combinedList. For each element, if it’s not already present in uniqueList, add it to uniqueList.
    7. Print combinedList and uniqueList.

 

Solution

import java.util.ArrayList;
import java.util.List;

public class CombineAndRemoveDuplicates {
    public static void main(String[] args) {
        // 1. Create two ArrayLists of String objects:
        List list1 = new ArrayList<>();
        list1.add("apple");
        list1.add("banana");
        list1.add("orange");
        list1.add("apple");

        List list2 = new ArrayList<>();
        list2.add("banana");
        list2.add("grape");
        list2.add("kiwi");
        list2.add("orange");

        // 2. Create a new ArrayList called combinedList.
        List combinedList = new ArrayList<>();

        // 3. Add all elements from list1 to combinedList.
        combinedList.addAll(list1);

        // 4. Add all elements from list2 to combinedList.
        combinedList.addAll(list2);

        // 5. Create another new ArrayList called uniqueList.
        List uniqueList = new ArrayList<>();

        // 6. Iterate through combinedList. For each element, if it's not already present in uniqueList, add it to uniqueList.
        for (String item : combinedList) {
            if (!uniqueList.contains(item)) {
                uniqueList.add(item);
            }
        }

        // 7. Print combinedList and uniqueList.
        System.out.println("Combined List: " + combinedList);
        System.out.println("Unique List: " + uniqueList);
    }
}


 

Exercise 3: Sorting Strings by Length

  • Goal: Implement custom sorting logic with ArrayList.
  • Task:
    1. Create an ArrayList of String objects: “short”, “longerstring”, “medium”, “a”, “verylongstringindeed”.
    2. Sort the ArrayList based on the length of the strings in ascending order. (Hint: You’ll need to use Collections.sort() with a custom Comparator).
    3. Print the sorted ArrayList.

Solution

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortByLength {
    public static void main(String[] args) {
        // 1. Create an ArrayList of String objects: "short", "longerstring", "medium", "a", "verylongstringindeed".
        List strings = new ArrayList<>();
        strings.add("short");
        strings.add("longerstring");
        strings.add("medium");
        strings.add("a");
        strings.add("verylongstringindeed");

        // 2. Sort the ArrayList based on the length of the strings in ascending order.
        Collections.sort(strings, Comparator.comparingInt(String::length));

        // 3. Print the sorted ArrayList.
        System.out.println("Sorted by Length: " + strings);
    }
}


 

Exercise 4: Implementing a Simple To-Do List

  • Goal: Simulate a real-world use case of ArrayList.
  • Task:
    1. Create an ArrayList to store to-do items (as String objects).
    2. Implement the following functionalities using methods:
      • addTask(String task): Adds a new task to the list.
      • viewTasks(): Prints all the tasks in the list with their index.
      • markAsDone(int index): Removes the task at the given index. Handle invalid index input gracefully.
    3. Demonstrate the usage of these methods by adding, viewing, and marking a couple of tasks as done.

Solution

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class TodoList {
    private List tasks;

    public TodoList() {
        this.tasks = new ArrayList<>();
    }

    public void addTask(String task) {
        this.tasks.add(task);
        System.out.println("Task '" + task + "' added.");
    }

    public void viewTasks() {
        if (tasks.isEmpty()) {
            System.out.println("Your to-do list is empty.");
        } else {
            System.out.println("--- To-Do List ---");
            for (int i = 0; i < tasks.size(); i++) {
                System.out.println((i + 1) + ". " + tasks.get(i));
            }
            System.out.println("------------------");
        }
    }

    public void markAsDone(int index) {
        if (index >= 1 && index <= tasks.size()) {
            String removedTask = tasks.remove(index - 1);
            System.out.println("Task '" + removedTask + "' marked as done (removed).");
        } else {
            System.out.println("Invalid task number.");
        }
    }

    public static void main(String[] args) {
        TodoList todoList = new TodoList();
        Scanner scanner = new Scanner(System.in);
        int choice;

        do {
            System.out.println("\n--- To-Do List Menu ---");
            System.out.println("1. Add Task");
            System.out.println("2. View Tasks");
            System.out.println("3. Mark Task as Done");
            System.out.println("4. Exit");
            System.out.print("Enter your choice: ");
            choice = scanner.nextInt();
            scanner.nextLine(); // Consume newline

            switch (choice) {
                case 1:
                    System.out.print("Enter task to add: ");
                    String newTask = scanner.nextLine();
                    todoList.addTask(newTask);
                    break;
                case 2:
                    todoList.viewTasks();
                    break;
                case 3:
                    System.out.print("Enter the number of the task to mark as done: ");
                    int taskNumber = scanner.nextInt();
                    todoList.markAsDone(taskNumber);
                    scanner.nextLine(); // Consume newline
                    break;
                case 4:
                    System.out.println("Exiting to-do list application. Goodbye!");
                    break;
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        } while (choice != 4);

        scanner.close();
    }
}


 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review