Han

Han Ferik

Home | Projects | AP CSA

Cheat Sheet

Tools: VSCode | Source Code: GitHub

This Java program demonstrates various basic, intermediate, and advanced operations on ArrayList collections. The class CheatSheet is structured to tackle different array manipulations, such as adding, updating, removing elements, and using loops for traversing the list. The first set of operations focuses on basic ArrayList operations. It begins by showing how to create and initialize an ArrayList of integers and add elements such as 10, 20, 30, 40, and 50. After adding these elements, the program prints the entire ArrayList to show the result. Next, it works with a String ArrayList containing names like "Alice," "Bob," and "Charlie." The program replaces "Bob" with "David" using the set() method and prints the updated list to reflect this change. The program then removes an element at a specific index—index 2—demonstrating the remove() method, and prints the modified list. Following this, the program checks if a specific name, "Alice," exists in the list using the contains() method, and prints "Found" if it is present, or "Not Found" if it isn't. The final part of this section involves finding the size of an ArrayList before and after adding elements, using the size() method to show how the list's size changes as elements are added.

The next section focuses on traversing ArrayLists. The program uses a for-each loop to print each element of an ArrayList of integers, specifically the numbers 1, 2, 3, 4, and 5. This demonstrates a simple and efficient way to loop through a collection. It also shows how to use a traditional for loop to traverse the list by accessing each element using the get() method and iterating through the list based on its size. The program then reverses the order of elements in an ArrayList of integers (10, 20, 30, 40) by using the Collections.reverse() method, and prints the reversed list. Following that, it calculates the sum of all elements in an ArrayList of integers by iterating through the list with a loop and adding the elements together. It then counts how many even numbers are in the list by checking if each number is divisible by 2 and printing the result.

Moving on to algorithmic tasks, the program tackles some common problems. It finds the maximum and minimum values in an ArrayList of integers using the Collections.max() and Collections.min() methods, respectively. The program also removes duplicate values from an ArrayList by iterating through the list and adding only unique elements to a new ArrayList. Afterward, it searches for the index of a specific element (e.g., "Bob") in a String ArrayList using the indexOf() method, printing the index of the element or -1 if it doesn't exist. The program also demonstrates how to insert a new element at a specific index in the ArrayList using the add(index, element) method. Finally, it merges two ArrayLists of integers into one by using the addAll() method and prints the combined result.

The last section covers advanced ArrayList operations. The program begins by sorting an ArrayList of integers in ascending order using the Collections.sort() method. It then removes all elements greater than a given value (50) by using the removeIf() method, which removes elements that meet a specific condition. Next, the program calculates the median value of an ArrayList of integers. To find the median, the list is first sorted, and then the middle element is retrieved to calculate the median. The program also counts how many times each unique element appears in the list using the Collections.frequency() method and prints the frequency of each element. Lastly, the program demonstrates how to shuffle the elements of an ArrayList randomly using the Collections.shuffle() method, printing the shuffled list to show the result.

Each of these operations illustrates the versatility of the ArrayList class in Java, covering a wide range of tasks from basic element manipulation to advanced operations such as sorting, removing duplicates, and calculating the median. The program is a comprehensive guide for working with ArrayList and shows how to use Java’s collection framework effectively for various tasks.


CheatSheet Java Code

CheatSheet Java Code


import java.util.ArrayList;
import java.util.Collections;

public class CheatSheet {

    public static void main(String[] args) {
        
        // 1. Create and Initialize an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);
        System.out.println("ArrayList: " + numbers);

        // 2. Access and Update Elements
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.set(1, "David"); // Replace "Bob" with "David"
        System.out.println("Updated ArrayList: " + names);

        // 3. Remove an Element
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(10);
        integers.add(20);
        integers.add(30);
        integers.add(40);
        integers.add(50);
        integers.remove(2); // Remove element at index 2
        System.out.println("ArrayList after removal: " + integers);

        // 4. Check if an Element Exists
        ArrayList<String> checkNames = new ArrayList<>();
        checkNames.add("Alice");
        checkNames.add("Bob");
        checkNames.add("Charlie");
        if (checkNames.contains("Alice")) {
            System.out.println("Found");
        } else {
            System.out.println("Not Found");
        }

        // 5. Find the Size of an ArrayList
        ArrayList<String> sizeList = new ArrayList<>();
        sizeList.add("A");
        sizeList.add("B");
        sizeList.add("C");
        System.out.println("Size before: " + sizeList.size());
        sizeList.add("D");
        sizeList.add("E");
        System.out.println("Size after: " + sizeList.size());

        // 6. Print All Elements Using a For-Each Loop
        ArrayList<Integer> forEachList = new ArrayList<>();
        forEachList.add(1);
        forEachList.add(2);
        forEachList.add(3);
        forEachList.add(4);
        forEachList.add(5);
        for (Integer num : forEachList) {
            System.out.println(num);
        }

        // 7. Print All Elements Using a For Loop
        ArrayList<String> forLoopList = new ArrayList<>();
        forLoopList.add("Alice");
        forLoopList.add("Bob");
        forLoopList.add("Charlie");
        for (int i = 0; i < forLoopList.size(); i++) {
            System.out.println(forLoopList.get(i));
        }

        // 8. Reverse the Elements in an ArrayList
        ArrayList<Integer> reverseList = new ArrayList<>();
        reverseList.add(10);
        reverseList.add(20);
        reverseList.add(30);
        reverseList.add(40);
        Collections.reverse(reverseList);
        System.out.println("Reversed ArrayList: " + reverseList);
    }

        // 9. Find the Sum of Elements in an ArrayList
        ArrayList<Integer> sumList = new ArrayList<>();
        sumList.add(1);
        sumList.add(2);
        sumList.add(3);
        sumList.add(4);
        sumList.add(5);
        int sum = 0;
        for (Integer num : sumList) {
            sum += num;
        }
        System.out.println("Sum of elements: " + sum);

        // 10. Count the Number of Even Numbers
        ArrayList<Integer> evenList = new ArrayList<>();
        evenList.add(1);
        evenList.add(2);
        evenList.add(3);
        evenList.add(4);
        evenList.add(5);
        int evenCount = 0;
        for (Integer num : evenList) {
            if (num % 2 == 0) {
                evenCount++;
            }
        }
        System.out.println("Number of even numbers: " + evenCount);

        // 11. Find the Maximum and Minimum Values
        ArrayList<Integer> maxMinList = new ArrayList<>();
        maxMinList.add(10);
        maxMinList.add(20);
        maxMinList.add(30);
        maxMinList.add(40);
        maxMinList.add(50);
        int max = Collections.max(maxMinList);
        int min = Collections.min(maxMinList);
        System.out.println("Maximum value: " + max);
        System.out.println("Minimum value: " + min);

        // 12. Remove All Duplicates
        ArrayList<Integer> duplicateList = new ArrayList<>();
        duplicateList.add(1);
        duplicateList.add(2);
        duplicateList.add(2);
        duplicateList.add(3);
        duplicateList.add(3);
        duplicateList.add(4);
        ArrayList<Integer> uniqueList = new ArrayList<>();
        for (Integer num : duplicateList) {
            if (!uniqueList.contains(num)) {
                uniqueList.add(num);
            }
        }
        System.out.println("Unique elements: " + uniqueList);

        // 13. Find the Index of an Element
        ArrayList<String> indexList = new ArrayList<>();
        indexList.add("Alice");
        indexList.add("Bob");
        indexList.add("Charlie");
        int index = indexList.indexOf("Bob");
        System.out.println("Index of 'Bob': " + index);

        // 14. Insert an Element at a Specific Index
        ArrayList<String> insertList = new ArrayList<>();
        insertList.add("Alice");
        insertList.add("Bob");
        insertList.add("Charlie");
        insertList.add(1, "David");
        System.out.println("ArrayList after insertion: " + insertList);

        // 15. Merge Two ArrayLists
        ArrayList<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        ArrayList<Integer> list2 = new ArrayList<>();
        list2.add(3);
        list2.add(4);
        list1.addAll(list2);
        System.out.println("Merged ArrayList: " + list1);

        // 16. Sort an ArrayList
        ArrayList<Integer> sortList = new ArrayList<>();
        sortList.add(30);
        sortList.add(10);
        sortList.add(20);
        Collections.sort(sortList);
        System.out.println("Sorted ArrayList: " + sortList);

        // 17. Reverse an ArrayList
        ArrayList<Integer> reverseList = new ArrayList<>();
        reverseList.add(10);
        reverseList.add(20);
        reverseList.add(30);
        Collections.reverse(reverseList);
        System.out.println("Reversed ArrayList: " + reverseList);

        // 18. Convert ArrayList to Array
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        arrayList.add("Cherry");
        String[] array = arrayList.toArray(new String[0]);
        System.out.println("Array from ArrayList: " + array);
        
    }

	// 19. Media Creates Reality
        // Defining the media impact and biases with examples
        String mediaExample = "In the 2016 U.S. Elections, media coverage played a significant role in shaping perceptions of the candidates.";
        System.out.println("Media Example: " + mediaExample);

        // 20. Counting Even Numbers in a List
        ArrayList<Integer> numberList = new ArrayList<>();
        numberList.add(1);
        numberList.add(2);
        numberList.add(3);
        numberList.add(4);
        numberList.add(5);
        int evenCount = 0;
        for (Integer num : numberList) {
            if (num % 2 == 0) {
                evenCount++;
            }
        }
        System.out.println("Number of even numbers: " + evenCount);
    }
}
    

Find me on the interwebs!

Github LinkedIn Instagram Facebook