Posted in

COLLECTION FRAMEWORK PROGRAMS AND ALGORITHMS IN JAVA

1. Write a program to reverse an ArrayList without using built-in reverse method?

Algorithm :

  • Start
  • Create ArrayList
    • An ArrayList<Integer> named list is created.
    • Elements 10, 20, 30, 40, 50 are added to the list in order.
    • At this point, list = [10, 20, 30, 40, 50].
  • Print Original List
    • Output: Original ArrayList: [10, 20, 30, 40, 50].
  • Reverse the ArrayList Manually
    • A for loop runs from index i = 0 to i < list.size() / 2. Here, list.size() is 5, so the loop runs for i = 0, 1.
  • First Iteration (i = 0)
    • temp = list.get(0) = 10
    • list.set(0, list.get(4)) = list.set(0, 50)list.set(4, temp) = list.set(4, 10)
    • List becomes: [50, 20, 30, 40, 10]
  • Second Iteration (i = 1)
    • temp = list.get(1) = 20
    • list.set(1, list.get(3)) = list.set(1, 40)list.set(3, temp) = list.set(3, 20)
    • List becomes: [50, 40, 30, 20, 10]
  • Loop ends as i = 2 is not less than list.size()/2.
  • Print Reversed List
    • Output: Reversed ArrayList: [50, 40, 30, 20, 10]
  • End

Program :

     import java.util.ArrayList;
      public class ReverseArrayList {
      public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
        System.out.println(“Original ArrayList: ” + list);
        // Reversing manually
        for (int i = 0; i < list.size() / 2; i++) {
            int temp = list.get(i);
            list.set(i, list.get(list.size() – 1 – i));
            list.set(list.size() – 1 – i, temp);
        }
        System.out.println(“Reversed ArrayList: ” + list);
    }
}

Output :

 Original ArrayList: [10, 20, 30, 40, 50]
 Reversed ArrayList: [50, 40, 30, 20, 10]

Explanation :

       The Java program demonstrates how to reverse an ArrayList manually without using built-in methods. It starts by populating the list with integers and then performs an in-place reversal using a for loop. The key idea is to swap the elements from the two ends of the list moving towards the center. In each iteration, the element at the ith index is swapped with the element at the (size – 1 – i)th index using a temporary variable. This process continues until the loop reaches the midpoint of the list. The algorithm is efficient as it only loops through half of the list and modifies it directly, using no extra space beyond a temporary variable.

2. Write a program to remove duplicates from an ArrayList while preserving order?

Algorithm :

  • Start
  • Create an ArrayList with Duplicates
    • An ArrayList<String> named listWithDuplicates is created.
    • Strings “apple”, “banana”, “apple”, “orange”, “banana”, “grape” are added.
    • At this point, listWithDuplicates = [apple, banana, apple, orange, banana, grape].
  • Print the Original List
    • Output: Original List: [apple, banana, apple, orange, banana, grape]
  • Remove Duplicates Using LinkedHashSet
    • A LinkedHashSet is created using the listWithDuplicates as input.
    • LinkedHashSet automatically eliminates duplicate entries.
    • It also preserves the insertion order, unlike HashSet.
    • So it retains the first occurrence of each unique element.
    • Result: set = [apple, banana, orange, grape]
  • Convert Set Back to ArrayList
    • A new ArrayList<String> named listWithoutDuplicates is created using the set.
    • This converts the deduplicated set back into a list format.
    • Final listWithoutDuplicates = [apple, banana, orange, grape]
  • Print the Result
    • Output: List after removing duplicates: [apple, banana, orange, grape]
  • End

Program :

     import java.util.ArrayList;
     import java.util.LinkedHashSet;
     public class RemoveDuplicates {
     public static void main(String[] args) {
        // Original ArrayList with duplicates
        ArrayList<String> listWithDuplicates = new ArrayList<>();
        listWithDuplicates.add(“apple”);
        listWithDuplicates.add(“banana”);
        listWithDuplicates.add(“apple”);
        listWithDuplicates.add(“orange”);
        listWithDuplicates.add(“banana”);
        listWithDuplicates.add(“grape”);
        System.out.println(“Original List: ” + listWithDuplicates);
      // Using LinkedHashSet to remove duplicates while preserving order
        LinkedHashSet<String> set = new LinkedHashSet<>(listWithDuplicates);
        ArrayList<String> listWithoutDuplicates = new ArrayList<>(set);
        System.out.println(“List after removing duplicates: ” + listWithoutDuplicates);
    }
}

Output :

Original List: [apple, banana, apple, orange, banana, grape]
 List after removing duplicates: [apple, banana, orange, grape]

Explanation :

This Java program removes duplicate elements from an ArrayList while maintaining the original insertion order of elements. The approach uses a LinkedHashSet, which combines the benefits of a HashSet (to remove duplicates) and a LinkedList (to preserve order). When the original list is passed to the LinkedHashSet, all duplicate entries are removed automatically, and the first occurrence of each unique string is preserved in their original order. The result is then converted back into an ArrayList for further use.

3. Write a program to find the frequency of each element in a list?

Algorithm :

  • Start
  • Create a List
    • An ArrayList<String> named list is initialized.
    • Elements added: “apple”, “banana”, “apple”, “orange”, “banana”, “apple”.
    • Final list: [apple, banana, apple, orange, banana, apple]
  • Print the Input List
    • Input List: [apple, banana, apple, orange, banana, apple]
  • Initialize a HashMap for Frequencies
  • A HashMap<String, Integer> named frequencyMap is created.
  • This will map each unique string (fruit name) to the number of times it appears in the list.
  •  Count Frequencies
  • Loop through each element (item) in the list:
  • Use frequencyMap.getOrDefault(item, 0):
  • If the item is already in the map, get its current count.
  • If not, default to 0.
  • Add 1 to the count and store it back with frequencyMap.put(item, count + 1).
  • Detailed Execution:
  • “apple” → not in map → count = 0 + 1 → store “apple” = 1
  • “banana” → not in map → count = 0 + 1 → store “banana” = 1
  • “apple” → in map with 1 → count = 1 + 1 → update “apple” = 2
  • “orange” → not in map → count = 0 + 1 → store “orange” = 1
  • “banana” → in map with 1 → count = 1 + 1 → update “banana” = 2
  • “apple” → in map with 2 → count = 2 + 1 → update “apple” = 3
  •  Final Frequency Map
  • {apple=3, banana=2, orange=1}
  • Print Frequencies
  • Loop through each key in the map and print:
  • End

Program :

    import java.util.ArrayList;
    import java.util.HashMap;
    public class FrequencyCounter {
    public static void main(String[] args) {
        // Sample list with repeated elements
        ArrayList<String> list = new ArrayList<>();
        list.add(“apple”);
        list.add(“banana”);
        list.add(“apple”);
        list.add(“orange”);
        list.add(“banana”);
        list.add(“apple”);
        System.out.println(“Input List: ” + list);
        // HashMap to store frequency
        HashMap<String, Integer> frequencyMap = new HashMap<>();
        for (String item : list) {
            frequencyMap.put(item, frequencyMap.getOrDefault(item, 0) + 1);
        }
        // Displaying the frequencies
        System.out.println(“Element Frequencies:”);
        for (String key : frequencyMap.keySet()) {
            System.out.println(key + “: ” + frequencyMap.get(key));
        }
    }
}

Output :

Input List: [apple, banana, apple, orange, banana, apple]
Element Frequencies:
apple: 3
banana: 2
orange: 1

Explanation :

         The program starts by creating an ArrayList containing repeated string elements. It then initializes a HashMap to store the frequency of each unique element. Using a for-each loop, it iterates through the list. For each item, it checks the current count in the map using getOrDefault and increments it by one. This updated count is stored back in the map using put. After processing all elements, the map contains each unique string as a key with its frequency as the value. The program then prints the frequencies by iterating through the map. This efficiently shows how often each item appears in the list.

4. Write a program to merge two lists into one without duplicates?

Algorithm :

  • Start
  • Create Two ArrayLists
    • list1 contains: “apple”, “banana”, “orange”
    • list2 contains: “banana”, “grape”, “apple”
  • Print Both Lists
  • Merge the Two Lists
    • A new ArrayList<String> named mergedList is created.
    • mergedList.addAll(list1) adds all elements from list1.
    • mergedList.addAll(list2) adds all elements from list2.
    • Resulting mergedList = [apple, banana, orange, banana, grape, apple]
  • Remove Duplicates While Preserving Order
    • A LinkedHashSet named uniqueSet is created from mergedList.
      • This automatically removes duplicates and keeps the insertion order.
      • uniqueSet = [apple, banana, orange, grape]
  • Convert Set Back to ArrayList
    • A new ArrayList<String> named finalList is created from uniqueSet.
    • Final finalList = [apple, banana, orange, grape]
  • Print the Final List
    • Merged List without Duplicates: [apple, banana, orange, grape]
  • End

Program :

     import java.util.ArrayList;
     import java.util.LinkedHashSet;
     public class MergeLists {
     public static void main(String[] args) {
        // First list
        ArrayList<String> list1 = new ArrayList<>();
        list1.add(“apple”);
        list1.add(“banana”);
        list1.add(“orange”);
        // Second list
        ArrayList<String> list2 = new ArrayList<>();
        list2.add(“banana”);
        list2.add(“grape”);
        list2.add(“apple”);
        System.out.println(“List 1: ” + list1);
        System.out.println(“List 2: ” + list2);
        // Merging both lists
        ArrayList<String> mergedList = new ArrayList<>();
        mergedList.addAll(list1);
        mergedList.addAll(list2);
        // Removing duplicates using LinkedHashSet (preserves order)
        LinkedHashSet<String> uniqueSet = new LinkedHashSet<>(mergedList);
        ArrayList<String> finalList = new ArrayList<>(uniqueSet);
        System.out.println(“Merged List without Duplicates: ” + finalList);
    }
}

Output :

  List 1: [apple, banana, orange]
  List 2: [banana, grape, apple]
  Merged List without Duplicates: [apple, banana, orange, grape]

Explanation :

            The program demonstrates how to merge two ArrayLists and remove duplicate elements while maintaining the original insertion order. It starts by creating two separate lists, list1 and list2, each containing a few string elements. Some elements are common in both lists. These lists are then combined into a new list, mergedList, using the addAll method, which appends the contents of both lists. To eliminate duplicates without disturbing the order of appearance, the program uses a LinkedHashSet. This collection automatically filters out repeated entries while preserving the sequence in which the elements were first added. Finally, the set is converted back into an ArrayList to obtain the result in list form, and the cleaned, merged list is displayed.

5. Write a program to find duplicates in a list using HashSet?

Algorithm :

  • Start
  • Create an ArrayList
    • The program initializes an ArrayList<String> named list.
    • It adds: “apple”, “banana”, “orange”, “apple”, “grape”, “banana”
    • Result: list = [apple, banana, orange, apple, grape, banana]
  • Print the Original List
    • Original List: [apple, banana, orange, apple, grape, banana]
  •  Initialize HashSets
    • seen: to track elements that have already been added
    • duplicates: to store elements that occur more than once
  • Iterate Through the List
    • For each item in the list:
      • seen.add(item) attempts to add the item.
      • If the item is already present, add() returns false.
      • In that case, the item is added to the duplicates set.
  • Detailed Iteration:
  • “apple” → not seen → add to seen
  • “banana” → not seen → add to seen
  • “orange” → not seen → add to seen
  • “apple” → already in seen → add to duplicates
  • “grape” → not seen → add to seen
  • “banana” → already in seen → add to duplicates
  • Final duplicates = [apple, banana]
  • Print Duplicates
  • End

Program :

     import java.util.ArrayList;
     import java.util.HashSet;
     public class FindDuplicates {
     public static void main(String[] args) {
        // Sample list with duplicates
        ArrayList<String> list = new ArrayList<>();
        list.add(“apple”);
        list.add(“banana”);
        list.add(“orange”);
        list.add(“apple”);
        list.add(“grape”);
        list.add(“banana”);
        System.out.println(“Original List: ” + list);
        // HashSet to track seen elements
        HashSet<String> seen = new HashSet<>();
        HashSet<String> duplicates = new HashSet<>();
        for (String item : list) {
            if (!seen.add(item)) {
                duplicates.add(item);
            }
        }
        System.out.println(“Duplicates Found: ” + duplicates);
    }
}

Output :

Original List: [apple, banana, orange, apple, grape, banana]
Duplicates Found: [apple, banana]

Explanation :

            This program identifies and prints duplicate elements from an ArrayList of strings. It first populates the list with some elements, including repeated ones like “apple” and “banana”. To detect duplicates efficiently, the program uses two HashSets. The first set, seen, keeps track of all elements that have been encountered. As the program iterates through the list, it tries to add each element to the seen set. If the element is already present (i.e., add() returns false), it means the element is a duplicate, and it is then added to the duplicates set. After completing the iteration, only elements that occurred more than once are stored in duplicates, which is then printed. This approach is efficient, as it ensures each element is checked only once and uses constant-time set operations.

6. Write a program to check if two lists have any elements in common (intersection using Set)?

Algorithm :

  • Start
    • list1 = [apple, banana, orange]
    • list2 = [grape, banana, melon]
  • Print Both Lists
  •     List 1: [apple, banana, orange] 
  •     List 2: [grape, banana, melon]
  •   Convert list1 to a HashSet
  •    A HashSet<String> named set is created using list1.
  •   Now, set = [apple, banana, orange]
  • Find Intersection with retainAll()
  • set.retainAll(list2) keeps only the elements in set that are also in list2.
  • Comparison:
  • “grape” → not in set
  • “banana” → in set → retained
  • “melon” → not in set
  • Result: set = [banana]
  •  Check for Common Elements
  • Since set is not empty, it prints the common elements.
  • Final Output
    • Common elements: [banana]
  • End

Program :

       import java.util.ArrayList;
       import java.util.HashSet;
       public class ListIntersection {
       public static void main(String[] args) {
        // First list
        ArrayList<String> list1 = new ArrayList<>();
        list1.add(“apple”);
        list1.add(“banana”);
        list1.add(“orange”);
        // Second list
        ArrayList<String> list2 = new ArrayList<>();
        list2.add(“grape”);
        list2.add(“banana”);
        list2.add(“melon”);
        System.out.println(“List 1: ” + list1);
        System.out.println(“List 2: ” + list2);
        // Convert first list to a HashSet
        HashSet<String> set = new HashSet<>(list1);
        // Retain only common elements
        set.retainAll(list2);
        if (set.isEmpty()) {
            System.out.println(“No common elements found.”);
        } else {
            System.out.println(“Common elements: ” + set);
        }
    }
}

Output :

   List 1: [apple, banana, orange]
   List 2: [grape, banana, melon]
   Common elements: [banana]

Explanation :

This program identifies and displays common elements (intersection) between two ArrayLists. It begins by creating two lists, each containing a few string values. To efficiently check for common values, it converts the first list into a HashSet, which allows fast lookup. The key operation is retainAll(), which modifies the set to keep only the elements that are also present in the second list. This effectively finds the intersection between the two lists. If no common elements exist, the set becomes empty, and the program prints a message indicating this. Otherwise, it displays the shared elements. In this example, “banana” is the only common item, and the program correctly outputs it.

7. Write a program to get all unique characters from a string using Set?

Algorithm :

  • Start
  • The string is: “programming”
    1. Print the Input String
  •  Input String: programming
  •  Create a LinkedHashSet
  • A LinkedHashSet<Character> named uniqueChars is created to store unique characters while preserving their order of appearance.
  • Convert String to Character Array and Iterate
  • The string is converted to a character array using input.toCharArray().
  • Each character is added to the set using add(), which automatically ignores duplicates.
  • Character Processing:
  • ‘p’ → added
  • ‘r’ → added
  • ‘o’ → added
  • ‘g’ → added
  • ‘r’ → already exists → ignored
  • ‘a’ → added
  • ‘m’ → added
  • ‘m’ → already exists → ignored
  • ‘i’ → added
  • ‘n’ → added
  • ‘g’ → already exists → ignored
  • Final set: [p, r, o, g, a, m, i, n]
  • Print Unique Characters
  •  Unique Characters: [p, r, o, g, a, m, i, n]
  • End

Program :

      import java.util.LinkedHashSet;
      import java.util.Set;
      public class UniqueCharacters {
      public static void main(String[] args) {
        String input = “programming”;
        System.out.println(“Input String: ” + input);
        // Using LinkedHashSet to maintain order and ensure uniqueness
        Set<Character> uniqueChars = new LinkedHashSet<>();
        for (char ch : input.toCharArray()) {
            uniqueChars.add(ch);
        }
        System.out.println(“Unique Characters: ” + uniqueChars);
    }
}

Output :

    Input String: programming
   Unique Characters: [p, r, o, g, a, m, i, n]

Explanation :

          This program extracts and prints the unique characters from a given string while preserving the original order of their appearance. It starts with a predefined string, “programming”, and converts it into a character array to iterate through each letter. A LinkedHashSet is used because it automatically filters out duplicates and maintains the insertion order. As each character is added, duplicates are ignored, ensuring that only the first occurrence is kept. Once the loop completes, the set contains all distinct characters in the order they first appeared in the string. The final output clearly shows these unique characters, making the program effective for simple character de-duplication with order preservation.

8. Write a program to use TreeSet to automatically sort and remove duplicates from an array?

Algorithm :

  • Start
  • The array numbers is declared as: {5, 3, 8, 3, 1, 9, 5, 2}
    1. Print the Original Array
    1. Create a TreeSet
  •  A TreeSet<Integer> named sortedSet is initialized.
  •  TreeSet automatically removes duplicates and sorts elements in ascending order.
  •   Iterate Through the Array and Add to TreeSet
  • Each number from the array is added to the TreeSet.
  • Duplicates like 3 and 5 are ignored automatically.
  • Step-by-step TreeSet population:
  • Add 5 → [5]
  • Add 3 → [3, 5]
  • Add 8 → [3, 5, 8]
  • Add 3 (duplicate) → ignored
  • Add 1 → [1, 3, 5, 8]
  • Add 9 → [1, 3, 5, 8, 9]
  • Add 5 (duplicate) → ignored
  • Add 2 → [1, 2, 3, 5, 8, 9]
  • Print the Sorted & Unique Set
  •   Sorted & Unique Elements: [1, 2, 3, 5, 8, 9]
  • End

Program :

  import java.util.Arrays;
  import java.util.Set;
  import java.util.TreeSet;
  public class TreeSetSort {
    public static void main(String[] args) {
        // Array with duplicates and unsorted values
        int[] numbers = {5, 3, 8, 3, 1, 9, 5, 2};
        System.out.println(“Original Array: ” + Arrays.toString(numbers));
        // Using TreeSet to remove duplicates and sort
        Set<Integer> sortedSet = new TreeSet<>();
        for (int num : numbers) {
            sortedSet.add(num);
        }
        System.out.println(“Sorted & Unique Elements: ” + sortedSet);
    }
}

Output :

Original Array: [5, 3, 8, 3, 1, 9, 5, 2]
Sorted & Unique Elements: [1, 2, 3, 5, 8, 9]

Explanation :

         This program demonstrates how to sort an array and remove duplicates using a TreeSet. It begins with an integer array that includes both unsorted and duplicate values. The array is printed for reference. A TreeSet is then used, which serves two purposes: it automatically removes any repeated elements and keeps the data sorted in ascending order. As the loop adds each element to the TreeSet, duplicates are ignored, and sorting is maintained internally. Once all elements have been processed, the resulting set contains only the distinct values from the array, arranged in order. This makes the TreeSet a powerful and efficient tool for simultaneously sorting and filtering unique values.

9. Write a program to count character frequency in a string using HashMap?

Algorithm :

  • Start
  • The string is: “programming”
    1. Print the Input String
  • Input String: programming
  •   Create a HashMap
  • A HashMap<Character, Integer> called charCountMap is created to store each character and its count.
  •   Convert String to Character Array and Iterate
  • The string is converted into a character array.
  • For each character:
  • If it exists in the map, increment its value by 1.
  • If not, add it with value 1 using getOrDefault().
  • Detailed Character Count Update:
  • ‘p’ → 1
  • ‘r’ → 1
  • ‘o’ → 1
  • ‘g’ → 1
  • ‘r’ → 2
  • ‘a’ → 1
  • ‘m’ → 1
  • ‘m’ → 2
  • ‘i’ → 1
  • ‘n’ → 1
  • ‘g’ → 2
  • Print Frequencies
  • Character Frequencies:
  • p: 1
  • r: 2
  • o: 1
  • g: 2
  • a: 1
  • m: 2
  • i: 1
  • n: 1
  • End

Program :

     import java.util.HashMap;
     import java.util.Map;
     public class CharFrequency {
      public static void main(String[] args) {
        String input = “programming”;
        System.out.println(“Input String: ” + input);
        // Create a HashMap to store character frequencies
        Map<Character, Integer> charCountMap = new HashMap<>();
        for (char ch : input.toCharArray()) {
            charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
        }
        // Display the character frequencies
        System.out.println(“Character Frequencies:”);
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            System.out.println(entry.getKey() + “: ” + entry.getValue());
        }
    }
}

Output :

 Input String: programming
Character Frequencies:
p: 1
r: 2
o: 1
g: 2
a: 1
m: 2
i: 1
n: 1

Explanation :

        This program calculates and displays the frequency of each character in a given string. It begins by defining a sample string, “programming”, and prints it. To count character frequencies, it uses a HashMap where each key is a character and its corresponding value is the count. The program iterates through the characters of the string using a loop, and for each character, it uses the getOrDefault() method to either fetch its existing count or initialize it to zero. The count is then incremented and updated in the map. Finally, the program loops through the map entries and prints each character along with how many times it appeared in the string.

10. Write a program to find the first non-repeating character in a string using LinkedHashMap?

Algorithm :

  • Start
  • The string is: “swiss”
    1. Print the Input String
  •   Input String: swiss
  •   Create a LinkedHashMap
  • LinkedHashMap<Character, Integer> charCountMap is used to count character frequencies while maintaining insertion order.
  •   Count Character Frequencies
  • Ierate through each character:
  • ‘s’ → 1
  • ‘w’ → 1
  • ‘i’ → 1
  • ‘s’ → 2
  • ‘s’ → 3
  • Final Map: {s=3, w=1, i=1}
  •  Find the First Non-Repeating Character
  • Loop through the map entries in order:
  • ‘s’ → count is 3 → skip
  • ‘w’ → count is 1 → this is the first non-repeating character
  •  Print Result and Exit
  • First non-repeating character: w
  • End

Program :

  import java.util.LinkedHashMap;
   import java.util.Map;
   public class FirstNonRepeatingChar {
    public static void main(String[] args) {
        String input = “swiss”;
        System.out.println(“Input String: ” + input);
        // LinkedHashMap maintains the insertion order
        LinkedHashMap<Character, Integer> charCountMap = new LinkedHashMap<>();
        // Count frequency of each character
        for (char ch : input.toCharArray()) {
            charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
        }
        // Find the first character with frequency 1
        for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            if (entry.getValue() == 1) {
                System.out.println(“First non-repeating character: ” + entry.getKey());
                return;
            }
        }
        System.out.println(“No non-repeating characters found.”);
    }
}

Output :

 Input String: swiss
First non-repeating character: w

Explanation :

       This program identifies the first non-repeating character in a given string. It begins by reading the input string “swiss” and printing it. To count character occurrences while preserving their order, it uses a LinkedHashMap, which maintains the sequence of insertion. As the program iterates through the characters, it updates the count for each character using getOrDefault(). Once the counting is complete, it traverses the map in the same order the characters appeared. The first entry with a count of 1 is identified and printed as the first non-repeating character. In this case, after skipping the repeated ‘s’, the program finds and prints ‘w’ as the first unique character.

11. Write a program to implement a word frequency counter from a file using Map?

Algorithm :

  • Start
  • Initialize the Input String
  • The input is a paragraph of text:
    “Hello world! Hello everyone. Welcome to the world of programming. Programming is fun. Everyone loves programming.”
  • Create a HashMap
  • Map<String, Integer> wordCountMap = new HashMap<>();
  • This map will store each word as a key and its frequency as the value.
  • Split the String into Words
  • input.split(“\\W+”) splits the string into words using non-word characters (punctuation, spaces) as delimiters.
  • Words like “Hello”, “world”, “programming” etc. are extracted.
  • Convert to Lowercase and Count Frequency
  • Each word is converted to lowercase to treat “Hello” and “hello” as the same word.
  • The frequency is updated using getOrDefault(word, 0) + 1.
  • Final Word Frequencies in the Map:
  •        hello: 2 
  •        world: 2 
  •        everyone: 2 
  •        welcome: 1 
  •        to: 1 
  •        the: 1 
  •       of: 1 
  •       programming: 3 
  •       is: 1 
  •       fun: 1 
  •       loves: 1 
  •  Display the Frequencies
    • The map is iterated using forEach() and each word with its frequency is printed.
  • End

Program :

     import java.util.*;
     public class WordFrequencyCounter {
      public static void main(String[] args) {
        String input = “Hello world! Hello everyone. Welcome to the world of programming. Programming is fun. Everyone loves programming.”;
        Map<String, Integer> wordCountMap = new HashMap<>(); 
        // Split the input string into words
        for (String word : input.split(“\\W+”)) {
            if (!word.isEmpty()) {
                word = word.toLowerCase();
                wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
            }
        }
        // Display the word frequencies
        wordCountMap.forEach((word, count) -> System.out.println(word + “: ” + count));
    }
}

Output :

 hello: 2
world: 2
everyone: 2
welcome: 1
to: 1
the: 1
of: 1
programming: 3
is: 1
fun: 1
loves: 1

Explanation :

     This program counts how many times each word appears in a given input paragraph. It uses a HashMap to store words as keys and their corresponding frequencies as values. The input string is split into individual words using a regular expression that removes punctuation and special characters. Each word is converted to lowercase to ensure consistency in counting. As the program processes each word, it updates the count in the map using getOrDefault(). Finally, the program iterates through the map and prints each word along with its frequency.

12. Write a Java program that sorts a list of Person objects based on their age using a custom comparator?

Algorithm :

  • Start
  • It contains two fields: name and age.
  • The constructor initializes these fields.
  • The toString() method formats output as “Name (Age)”.
  • Create a List of Person Objects
    • The people list is created using Arrays.asList():
      • “Alice”, 30
      • “Bob”, 25″Charlie”, 35
      • Sort the List by Age
  • people.sort(Comparator.comparingInt(p -> p.age));
  • This sorts the list in ascending order of age using a lambda expression.
    • Print the Sorted List
  • Each person in the sorted list is printed using the toString() method.
  • End

Program :

   import java.util.*;
   class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String toString() {
        return name + ” (” + age + “)”;
    }
}
public class SortByAge {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
            new Person(“Alice”, 30),
            new Person(“Bob”, 25),
            new Person(“Charlie”, 35)
        );
        // Sort using custom comparator by age
        people.sort(Comparator.comparingInt(p -> p.age));
        // Output
        for (Person p : people) {
            System.out.println(p);
        }
    }
}

Output :

   Bob (25)
   Alice (30)
   Charlie (35)

Explanation :

    This Java program demonstrates how to sort a list of custom objects using a comparator. A class Person is defined with fields for name and age, and a toString() method for display. In the main method, a list of Person objects is initialized with three entries. The list is then sorted based on age using Comparator.comparingInt(p -> p.age), which tells Java to compare the age field of each object. The sorted list is then printed, showing the people ordered from youngest to oldest.

13. Write a Java program to check if a given ArrayList contains a sublist?

Algorithm :

  • Start
  • mainList = [1, 2, 3, 4, 5, 6]
  • subList = [3, 4, 5]
  • Check for Sublist
  • Collections.indexOfSubList(mainList, subList) checks if subList appears as a sequence within mainList.
  • It returns the starting index of the sublist if found, otherwise -1.
  • Store the Result
    • contains = true because [3, 4, 5] appears in mainList starting from index 2.
  • Print Results
    • Main List: [1, 2, 3, 4, 5, 6] 
    • Sublist: [3, 4, 5] 
    • Contains Sublist? true
  • End

Program :

  import java.util.*;
     public class SublistCheck {
     public static void main(String[] args) {
        List<Integer> mainList = Arrays.asList(1, 2, 3, 4, 5, 6);
        List<Integer> subList = Arrays.asList(3, 4, 5);
        boolean contains = Collections.indexOfSubList(mainList, subList) != -1;
        System.out.println(“Main List: ” + mainList);
        System.out.println(“Sublist: ” + subList);
        System.out.println(“Contains Sublist? ” + contains);
    }
}

Output :

Main List: [1, 2, 3, 4, 5, 6]
Sublist: [3, 4, 5]
Contains Sublist? True

Explanation :

          This Java program checks whether a list contains a specific sequence of elements (a sublist). It uses the Collections.indexOfSubList() method, which searches for a sublist in a main list and returns the starting index if found or -1 otherwise. In this case, the main list [1, 2, 3, 4, 5, 6] contains the sublist [3, 4, 5] starting at index 2. Therefore, the result is true.

14. Write a Java program to remove all even numbers from a list of integers?

Algorithm :

  • Start
  • Initialize the List
    • numbers = [1, 2, 3, 4, 5, 6, 7, 8]
    • This list contains both odd and even integers.
  • Display Original List
    • Print the full list before any changes.
  • Remove Even Numbers
  • numbers.removeIf(n -> n % 2 == 0)
  • This uses a lambda expression to remove numbers divisible by 2 (even numbers).
    • Display Updated List
  • After removing even numbers, the list becomes [1, 3, 5, 7].
  • End

Program :

  import java.util.*;
   public class RemoveEven {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
        System.out.println(“Original List: ” + numbers);
        numbers.removeIf(n -> n % 2 == 0);  // Remove even numbers
        System.out.println(“After Removing Even Numbers: ” + numbers);
    }
}

Output :

Original List: [1, 2, 3, 4, 5, 6, 7, 8]
 After Removing Even Numbers: [1, 3, 5, 7]

Explanation :

      This program demonstrates how to remove even numbers from a list using Java’s removeIf() method. It begins by creating a list of integers from 1 to 8. The removeIf() method is then applied with a lambda expression that checks if a number is even (n % 2 == 0). If the condition is true, the number is removed from the list. As a result, only the odd numbers remain.

15. Write a Java program that creates a PriorityQueue of integers and demonstrates the behavior of the queue (insert elements, peek, poll)?

Algorithm :

  • Start
  • A PriorityQueue named pq is created, which automatically arranges elements in natural (ascending) order.
    • Add Elements
  • Insert: 30, 10, 20, 5
  • Internally, the queue is structured as a min-heap, so the smallest element (5) becomes the head.
    • Print the Queue
  • System.out.println(“PriorityQueue: ” + pq);
  • Output may not look sorted, but the smallest element is always at the head.
    • Peek Operation
  • pq.peek() returns the head (smallest element) without removing it — in this case, 5.
    •  Poll Operation
  • pq.poll() removes and returns the head — removes 5.
    • Print Queue After Polling
  • Now the next smallest element (10) becomes the new head.
  • End

Program :

    import java.util.PriorityQueue;
     public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        // Insert elements
        pq.add(30);
        pq.add(10);
        pq.add(20);
        pq.add(5);
        System.out.println(“PriorityQueue: ” + pq);
        // Peek – view the head of the queue
        System.out.println(“Peek (head): ” + pq.peek());
        // Poll – remove the head
        System.out.println(“Poll (remove head): ” + pq.poll());
        // Queue after polling
        System.out.println(“PriorityQueue after poll: ” + pq);
    }
}

Output :

PriorityQueue: [5, 10, 20, 30]
Peek (head): 5
Poll (remove head): 5
PriorityQueue after poll: [10, 30, 20]

Explanation :

         This Java program demonstrates how a PriorityQueue manages elements based on their natural ordering. Elements 30, 10, 20, and 5 are added to the queue. Although printing the queue does not display them in sorted order, the smallest element is always accessible at the head due to the internal heap structure. The peek() method allows viewing the head without removing it, while poll() removes the head. After polling, the next smallest element becomes the head. This behavior makes PriorityQueue ideal for problems requiring efficient access to minimum or maximum elements.

16. Write a Java program to find the union of two lists of integers?

Algorithm :

  • Start
  • Initialize Two Lists
  • list1 = [1, 2, 3, 4]
  • list2 = [3, 4, 5, 6]
  • Create a Set to Store the Union
  • Use a LinkedHashSet named unionSet to maintain insertion order and remove duplicates.
    • Add All Elements from Both Lists
  • unionSet.addAll(list1) → adds [1, 2, 3, 4]
  • unionSet.addAll(list2) → adds 5, 6 (skips 3, 4 since already present)
    • Convert Set to List
  • unionList = new ArrayList<>(unionSet) → creates a list: [1, 2, 3, 4, 5, 6]
  • Print Results
  • Output each list and the final union list.
  • End

Program :

    import java.util.*;
    public class ListUnion {
     public static void main(String[] args) {
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
        List<Integer> list2 = Arrays.asList(3, 4, 5, 6);
        // Use a Set to remove duplicates
        Set<Integer> unionSet = new LinkedHashSet<>();
        unionSet.addAll(list1);
        unionSet.addAll(list2);
        // Convert to list if needed
        List<Integer> unionList = new ArrayList<>(unionSet);
        System.out.println(“List 1: ” + list1);
        System.out.println(“List 2: ” + list2);
        System.out.println(“Union: ” + unionList);
    }
}

Output :

   List 1: [1, 2, 3, 4]
   List 2: [3, 4, 5, 6]
   Union: [1, 2, 3, 4, 5, 6]

Explanation :

This program demonstrates how to compute the union of two lists using a LinkedHashSet. The first and second lists may contain overlapping values. By adding all elements from both lists to a LinkedHashSet, duplicates are automatically removed, and the original order of first appearance is preserved. The set is then converted back to a list for further use or output. This approach efficiently combines two lists while ensuring all elements are unique and ordered as initially encountered.

17. Write a Java program to demonstrate the use of LinkedHashMap where you insert some elements and print the map to show the order of insertion?

Algorithm :

  • Start
  • Create a LinkedHashMap
    • A LinkedHashMap<Integer, String> named map is initialized. It stores key-value pairs and maintains insertion order.
  • Insert Key-Value Pairs
  • map.put(101, “Apple”)
  • map.put(102, “Banana”)
  • map.put(103, “Cherry”)
  • map.put(104, “Date”)
  • Iterate Through the Map
  • Using a for-each loop over map.entrySet(), each key-value pair is printed in the order they were added.
  • End

Program :

   import java.util.LinkedHashMap;
   import java.util.Map;
   public class LinkedHashMapDemo {
    public static void main(String[] args) {
        // Create a LinkedHashMap
        LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
        // Insert elements
        map.put(101, “Apple”);
        map.put(102, “Banana”);
        map.put(103, “Cherry”);
        map.put(104, “Date”);
        // Print the map
        System.out.println(“LinkedHashMap (Insertion Order):”);
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ” => ” + entry.getValue());
        }
    }
}

Output :

 LinkedHashMap (Insertion Order):
101 => Apple
102 => Banana
103 => Cherry
104 => Date

Explanation :

This program illustrates how a LinkedHashMap preserves the insertion order of elements. Unlike HashMap, which does not guarantee any specific order, LinkedHashMap ensures that elements are retrieved in the exact order in which they were inserted. The key-value pairs (101 to “Apple”, and so on) are added to the map and then iterated using an enhanced for loop. When printed, the output reflects the original order of insertion, demonstrating one of the key advantages of using LinkedHashMap in Java.

18. Write a Java program that sorts a TreeSet in reverse order?

Algorithm :

  • Start
  • TreeSet<Integer> numbers = new TreeSet<>(Collections.reverseOrder());
  • This initializes a TreeSet that stores elements in descending order.
    1. Add Elements to the TreeSet
  • numbers.add(10)
  • numbers.add(5)
  • numbers.add(20)
  • numbers.add(15)
  • TreeSet automatically sorts and stores them in reverse (i.e., descending) order: [20, 15, 10, 5].
    • Print the TreeSet
  • Outputs the elements in descending order.
  • End

Program :

   import java.util.*;
   public class TreeSetReverseOrder {
    public static void main(String[] args) {
        // Create TreeSet with reverse order comparator
        TreeSet<Integer> numbers = new TreeSet<>(Collections.reverseOrder());
        // Add elements
        numbers.add(10);
        numbers.add(5);
        numbers.add(20);
        numbers.add(15);
        // Print the TreeSet
        System.out.println(“TreeSet in Reverse Order: ” + numbers);
    }
}

Output :

TreeSet in Reverse Order: [20, 15, 10, 5]

Explanation :

       This Java program demonstrates how to use a TreeSet with a custom reverse order comparator. By passing Collections.reverseOrder() to the TreeSet constructor, it ensures that all elements are stored in descending rather than the default ascending order. As elements are added, the TreeSet automatically organizes them based on the comparator logic. When printed, the numbers appear from largest to smallest, showcasing the automatic sorting behavior of TreeSet when a comparator is provided.

19. Write a Java program that checks if a list is empty and returns a boolean result?

Algorithm :

  • Start
  • List<String> items = new ArrayList<>();
  • Initializes an empty list of strings.
    1.  (Optional) Add Elements to the List
  • The line to add “Apple” is commented out, so the list remains empty.
    1.  Check if the List is Empty
  • isEmpty() method is called on the list.
  • Since no elements were added, isEmpty returns true.
    1.   Print the List and the Check Result
  • Displays the empty list [] and prints true for the emptiness check.
  • End

Program :

   import java.util.*; 
    public class ListEmptyCheck {
    public static void main(String[] args) {
        List<String> items = new ArrayList<>();
        // Uncomment below to add items and test non-empty case
        // items.add(“Apple”);
        boolean isEmpty = items.isEmpty();
        System.out.println(“List: ” + items);
        System.out.println(“Is the list empty? ” + isEmpty);
    }
}

Output :

List: []
Is the list empty? True

Explanation :

        This program demonstrates how to check whether a List is empty in Java using the isEmpty() method. An ArrayList of strings is created and left empty because the item-adding line is commented out. When the program checks the list using isEmpty(), it returns true, indicating the list has no elements. The result is then printed alongside the current state of the list. This is a useful approach for validating if a list has any data before performing operations like iteration or access.

20. Write a Java program to convert an ArrayList to a LinkedList?

Algorithm :

  • Start
  • arrayList is initialized and three elements are added: “Apple”, “Banana”, and “Cherry”.
    • Convert ArrayList to LinkedList
  • A LinkedList named linkedList is created using the constructor that accepts a collection (new LinkedList<>(arrayList)).
  • This copies all elements from arrayList into the new linkedList.
    • Print Both Lists
  • The program prints the contents of both arrayList and linkedList to show they contain the same data.

Program :

     import java.util.*;
     public class ConvertList {
      public static void main(String[] args) {
         // Create an ArrayList
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(“Apple”);
        arrayList.add(“Banana”);
        arrayList.add(“Cherry”);
        // Convert to LinkedList
        LinkedList<String> linkedList = new LinkedList<>(arrayList);
        // Print both lists
        System.out.println(“ArrayList: ” + arrayList);
        System.out.println(“Converted LinkedList: ” + linkedList);
    }
}

Output :

   ArrayList: [Apple, Banana, Cherry]
   Converted LinkedList: [Apple, Banana, Cherry]

Explanation :

       This program demonstrates how to convert an ArrayList to a LinkedList in Java. An ArrayList is first created and populated with three fruit names. Then, a new LinkedList is created by passing the ArrayList to its constructor, which copies all elements from the ArrayList. This technique is commonly used when you need to switch to a data structure that offers different performance characteristics (e.g., LinkedList allows faster insertions and deletions at the beginning or middle). Finally, both lists are printed to confirm that the conversion preserved the order and content of elements.

Leave a Reply

Your email address will not be published. Required fields are marked *