Java Programming

  • List Interface in Java : Complete Guide for Developers

    The List interface in Java represents an ordered collection that allows duplicate elements and provides positional access. It is a part of the java.util package and extends the Collection interface. Lists are commonly used when the order of elements matters, and when you need to access elements by their index position.

    Key Characteristics of List:

    • Ordered Collection: Elements in a List are ordered, meaning they maintain the sequence in which they were inserted.
    • Allows Duplicates: A List can contain multiple occurrences of the same element.
    • Indexed Access: Elements can be accessed using an integer index, with the first element at index 0.
    • Null Elements: List implementations allow the inclusion of null elements.

    Declaration of the Java List Interface

    The List interface in Java is declared as follows:

    public interface List<E> extends Collection<E> { }

    It represents an ordered collection that allows duplicate elements and provides positional access.

    Since List is an interface, we cannot instantiate it directly. Instead, we create an instance of a class that implements it, such as ArrayList, LinkedList, or Vector.

    Example:

    import java.util.List;
    import java.util.ArrayList;
    
    public class ListDemo {
        public static void main(String[] args) {
            // Instantiate a List using ArrayList
            List<String> list = new ArrayList<>();  // Using ArrayList
            list.add("Java");
            list.add("Python");
            list.add("C++");
    
            System.out.println(list); //Output: [Java, Python, C++]
        }
    }

    βœ… Explanation:

    • List<String> β†’ The generic type <String> specifies that this list will store String elements.
    • new ArrayList<>() β†’ We are creating an ArrayList instance that implements the List interface.

    Common Implementations of List:

    List Implementation classes

    Java provides several classes that implement the List interface, each with its own characteristics and use cases:

    1. ArrayList: A resizable array implementation of the List interface. It allows fast random access and is efficient for storing and accessing data. However, adding or removing elements (except at the end) can be slow due to the need to shift elements.
    2. LinkedList: A doubly-linked list implementation of the List interface. It allows for efficient insertion or removal of elements from both ends and from the middle of the list. However, it provides slower access to elements by index compared to ArrayList.
    3. Vector: An older implementation of the List interface. It is similar to ArrayList but is synchronized, making it thread-safe. However, this synchronization comes with a performance cost.
    4. Stack: A subclass of Vector that represents a last-in, first-out stack of objects. It provides methods like push(), pop(), and peek() to operate on the stack.
    5. CopyOnWriteArrayList: A thread-safe variant of ArrayList where all mutative operations (like add, set, etc.) are implemented by making a fresh copy of the underlying array. This is useful when you have a list that is frequently read but infrequently modified.

    Java List – Operations in Detail

    The List interface in Java (part of the Collection Framework) represents an ordered collection that can contain duplicate elements.
    Common implementations: ArrayList, LinkedList, CopyOnWriteArrayList, Vector.

    1. Creating a List

    import java.util.*;
    
    public class ListCreation {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();  // Using ArrayList
            list.add("Java");
            list.add("Python");
            list.add("C++");
    
            System.out.println(list); // [Java, Python, C++]
        }
    }

    2. Adding Elements

    • add(E e) β†’ Adds element at the end.
    • add(int index, E e) β†’ Inserts element at a specific index.
    list.add("Go");            // Adds at end
    list.add(1, "Kotlin");     // Inserts at index 1
    

    3. Accessing Elements

    • get(int index) β†’ Retrieves element at given index.
    System.out.println(list.get(0));  // Java
    System.out.println(list.get(2));  // Kotlin
    

    4. Updating Elements

    • set(int index, E e) β†’ Replaces element at index.
    list.set(2, "Rust");  
    System.out.println(list); // [Java, Kotlin, Rust, Go]
    

    5. Removing Elements

    • remove(int index) β†’ Removes by index.
    • remove(Object o) β†’ Removes first occurrence of object.
    • clear() β†’ Removes all elements.
    list.remove("Kotlin");   // Removes element
    list.remove(1);          // Removes by index
    list.clear();            // Removes all
    

    6. Searching in List

    • contains(Object o) β†’ Checks if element exists.
    • indexOf(Object o) β†’ First index of element, or -1 if not found.
    • lastIndexOf(Object o) β†’ Last index of element.
    System.out.println(list.contains("Java"));   // true
    System.out.println(list.indexOf("Java"));    // 0
    System.out.println(list.lastIndexOf("Go"));  // 3
    

    7. Iterating Over a List

    • For-each Loop
    for (String lang: list) {
      System.out.println(lang);
    }
    • Iterator
    Iterator < String > itr = list.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
    • ListIterator (Bidirectional)
    ListIterator < String > litr = list.listIterator();
    while (litr.hasNext()) {
      System.out.println(litr.next());
    }
    • Java 8+ forEach with Lambda
    list.forEach(System.out::println);
    

    8. Sorting a List

    Collections.sort(list);                  // Natural order
    list.sort(Comparator.reverseOrder());    // Reverse order
    

    9. Sublist Operation

    List < String > sub = list.subList(1, 3);
    System.out.println(sub); // [Python, C++]

    10. Converting List to Array

    String[] arr = list.toArray(new String[0]);
    System.out.println(Arrays.toString(arr));
    

    11. Streams & Functional Operations (Java 8+)

    list.stream()
        .filter(lang -> lang.startsWith("J"))
        .forEach(System.out::println);   // Java

    12. Checking if an Element is Present in a List

    The List interface provides methods to check whether an element exists inside a list.

    βœ… Methods Used

    1. contains(Object o) β†’ Returns true if the list contains the specified element, else false.
    2. indexOf(Object o) β†’ Returns the first index of the element, or -1 if not found.
    3. lastIndexOf(Object o) β†’ Returns the last index of the element, or -1 if not found.

    Example

    import java.util.*;
    
    public class ListSearchExample {
        public static void main(String[] args) {
            List<String> languages = new ArrayList<>();
            languages.add("Java");
            languages.add("Python");
            languages.add("C++");
            languages.add("Java"); // duplicate
    
            // 1. contains()
            System.out.println(languages.contains("Java"));   // true
            System.out.println(languages.contains("Rust"));   // false
    
            // 2. indexOf()
            System.out.println(languages.indexOf("Java"));    // 0 (first occurrence)
            System.out.println(languages.indexOf("Rust"));    // -1 (not found)
    
            // 3. lastIndexOf()
            System.out.println(languages.lastIndexOf("Java")); // 3 (last occurrence)
        }
    }
    

    Output

    true
    false
    0
    -1
    3

    πŸ“Œ Summary Table of List Operations

    OperationMethod ExampleDescription
    Addadd("Java"),addAll()Insert element
    Accessget(0)Retrieve element
    Updateset(1, "Kotlin")Replace element
    Removeremove("Java"),removeAll(), retainAll(), clear()Remove by value
    Searchcontains("Java"),indexOf(), lastIndexOf()Check existence
    IterateforEach(System.out::println),iterator(), listIterator(), spliterator()Traverse list
    SortCollections.sort(list)Sort elements
    SublistsubList(1, 3)Extract portion
    ConverttoArray(), size(), isEmpty()Convert to array, Get size of elements, Check if the list is empty

    βœ… In short:
    The List interface in Java provides powerful operations to manage ordered collections, making it one of the most widely used data structures in Java applications.

  • Java Collection Framework – A Complete Guide with Examples

    Introduction

    Why Collections Came into Picture:
    ✍️In Java, arrays have a fixed size and lack built-in methods for easy manipulation like adding, removing, or searching elements. To overcome these limitations, the Collection Framework was introduced, providing dynamic data structures with rich utility methods. For a detailed understanding of arrays in Java, you can check Java Arrays Tutorial

    The Java Collection Framework (JCF) is a unified architecture for storing and manipulating groups of objects. It provides ready-to-use data structures (like List, Set, Map, Queue) and algorithms (like sorting, searching, iteration).

    Instead of writing complex data structures manually, Java developers can use these pre-built and optimized collections.

    πŸ‘‰ The framework is part of java.util package and was introduced in Java 2 (JDK 1.2), but has been enhanced with each release up to the latest Java 25.

    Why Use Collection Framework?

    • Reduces development effort β†’ ready-to-use data structures.
    • Improves performance β†’ optimized implementations.
    • Increases code quality β†’ reusable, consistent APIs.
    • Type safety with Generics (introduced in Java 5).
    • Concurrent utilities (from Java 5 onwards, updated till Java 25).

    Collection Framework Hierarchy

    At the top level, we have two main root interfaces:

    1. Collection Interface (java.util.Collection)
      • Extended by List, Set, and Queue.
    2. Map Interface (java.util.Map)
      • A separate hierarchy for key-value pairs.

    Hierarchy Overview:

                                              Iterable
                                                 |
                                   +--------------+-------------------------+
                                   |                                        |
                          +-----Collection---------------+                 Map
                        /            |                   |                  |
                       /             |                   |                  |
                    List            Set----+            Queue            SortedMap
                    /                |      \            |                  |
        +--------+----------+        |       \           |                  |
        |        |          |    SortedSet  HashSet    Deque          NavigableMap
    ArrayList Vector LinkedList      |         |
                                NavigableSet LinkedHashSet
                                     |
                                  TreeSet

    Key Interfaces and Classes

    At the heart of the Java Collections Framework are a set of key interfaces β€” Collection, List, Set, Queue, Deque, and Map. These interfaces establish the contracts that different collection classes must follow, providing guidelines for how data can be stored, accessed, and manipulated.

    • List Interface
    • Set Interface
    • Queue Interface
    • Deque Interface
    • Map Interface

    1. List Interface

    Represents an ordered collection that allows duplicate elements and provides positional access. Lists include dynamic arrays, linked structures, and legacy classes designed for sequential storage.

    • Index-based access.

    Popular Implementations:

    • ArrayList
    • LinkedList
    • Vector
    • Stack
    • CopyOnWriteArrayList

    βœ… Example:

    import java.util.*;
    
    public class ListExample {
        public static void main(String[] args) {
            List<String> fruits = new ArrayList<>();
            fruits.add("Apple");
            fruits.add("Banana");
            fruits.add("Mango");
            fruits.add("Apple"); // allows duplicates
    
            System.out.println("Fruits List: " + fruits);
        }
    }
    

    2. Set Interface

    Represents a collection that does not allow duplicate elements. Sets are used to model mathematical sets and may or may not preserve insertion order, depending on the implementation.

    Popular Implementations:

    • HashSet
    • LinkedHashSet
    • TreeSet
    • CopyOnWriteArraySet

    βœ… Example:

    import java.util.*;
    
    public class SetExample {
        public static void main(String[] args) {
            Set<String> names = new HashSet<>();
            names.add("Simone");
            names.add("Jeremy");
            names.add("Simone"); // ignored
    
            System.out.println("Names: " + names);
        }
    }
    

    3. Queue Interface

    Represents a collection designed for holding elements prior to processing. Queues typically follow FIFO (First-In-First-Out) order, but priority-based or custom orderings are also possible.

    Popular Implementations:

    • LinkedList
    • PriorityQueue
    • ArrayDeque
    • ConcurrentLinkedQueue
    • LinkedBlockingQueue

    βœ… Example:

    import java.util.*;
    
    public class QueueExample {
        public static void main(String[] args) {
            Queue<Integer> queue = new LinkedList<>();
            queue.add(10);
            queue.add(20);
            queue.add(30);
    
            System.out.println("Queue: " + queue);
            System.out.println("Removed: " + queue.poll()); // removes first
            System.out.println("After removal: " + queue);
        }
    }
    

    4. Deque Interface

    A double-ended queue that supports element insertion and removal at both ends. Deques can function as stacks (LIFO) or queues (FIFO), providing flexible access patterns.

    Popular Implementations:

    • ArrayDeque.
    • ConcurrentLinkedDeque
    • LinkedBlockingDeque
    • LinkedList

    βœ… Example:

    import java.util.*;
    
    public class DequeExample {
        public static void main(String[] args) {
            Deque<String> dq = new ArrayDeque<>();
            dq.addFirst("Start");
            dq.addLast("End");
    
            System.out.println(dq);
        }
    }
    

    5. Map Interface

    Represents a collection of key–value pairs, where keys are unique and each key maps to exactly one value. Maps are not true collections but provide a way to store and retrieve data based on unique identifiers.

    • Keys are unique, values can be duplicate.

    Popular Implementations:

    • HashMap
    • LinkedHashMap
    • TreeMap
    • Hashtable
    • ConcurrentHashMap (thread-safe)

    βœ… Example:

    import java.util.*;
    
    public class MapExample {
        public static void main(String[] args) {
            Map<Integer, String> students = new HashMap<>();
            students.put(1, "Alice");
            students.put(2, "Bob");
            students.put(3, "Charlie");
    
            System.out.println("Students: " + students);
            System.out.println("Student with ID 2: " + students.get(2));
        }
    }
    

    6.Utility Class: Collections

    The Collections class (part of java.util package) is a utility class that provides static methods to operate on or return collections.

    It is different from the Collections Framework itself. The Collections Framework provides data structures (List, Set, Map, etc.), while the Collections class provides algorithms and helper methods to work with those data structures.

    Key Features of Collections Class

    1. Algorithms β†’ Sorting, Searching, Shuffling, Reversing, Rotating, etc.
    2. Synchronization Wrappers β†’ Convert non-thread-safe collections into thread-safe ones.
    3. Read-only Wrappers β†’ Create immutable collections.
    4. Utility Methods β†’ Frequency count, finding min/max, filling collections, etc.

    Method :

    MethodDescriptionExample
    sort(List<T> list)Sorts the list in ascending order.Collections.sort(list);
    reverse(List<?> list)Reverses the list order.Collections.reverse(list);
    min(Collection<? extends T> coll)Returns minimum element.Collections.min(list);
    max(Collection<? extends T> coll)Returns maximum element.Collections.max(list);
    frequency(Collection<?> c, Object o)Counts frequency of element.Collections.frequency(list, "Java");

    βœ… Example:

    Example 1: Sorting and Reversing

    import java.util.*;
    
    public class CollectionsExample1 {
        public static void main(String[] args) {
            List<String> names = new ArrayList<>();
            names.add("Aryan");
            names.add("Ashish");
            names.add("bhasker");
            names.add("Devid");
    
            // Sorting (Ascending Order)
            Collections.sort(names);
            System.out.println("Sorted List: " + names);
    
            // Reversing
            Collections.reverse(names);
            System.out.println("Reversed List: " + names);
    
            // Shuffling
            Collections.shuffle(names);
            System.out.println("Shuffled List: " + names);
        }
    }
    

    Output (may vary due to shuffle):

    Sorted List: [Aryan, Ashish, Bhasker, Devid]
    Reversed List: [Devid, Bhasker, Ashish, Aryan]
    Shuffled List: [Ashish, Devid, Bhasker, Aryan]   // shuffle can change each time
    

    Example 2: Finding Min, Max, and Frequency

    import java.util.*;
    
    public class CollectionsExample2 {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(10, 20, 30, 10, 50, 10);
    
            int min = Collections.min(numbers);
            int max = Collections.max(numbers);
            int freq = Collections.frequency(numbers, 10);
    
            System.out.println("Minimum: " + min);
            System.out.println("Maximum: " + max);
            System.out.println("Frequency of 10: " + freq);
        }
    }
    

    Output:

    Minimum: 10  
    Maximum: 50  
    Frequency of 10: 3  
    

    Example 3: Creating Read-only and Synchronized Collections

    import java.util.*;
    
    public class CollectionsExample3 {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            list.add("Java");
            list.add("Python");
            list.add("C++");
    
            // Unmodifiable (Read-only) List
            List<String> unmodifiableList = Collections.unmodifiableList(list);
            System.out.println("Unmodifiable List: " + unmodifiableList);
            // unmodifiableList.add("Go"); // Throws UnsupportedOperationException
    
            // Synchronized List (Thread-safe wrapper)
            List<String> syncList = Collections.synchronizedList(list);
            System.out.println("Synchronized List: " + syncList);
        }
    }
  • How to remove elements from a list without writing loops or risking ConcurrentModificationException in Java?

    Problem

    How to remove elements from a list without writing loops or risking ConcurrentModificationException?

    Example Code

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class RemoveIfDemo {
        public static void main(String[] args) {
            List<Integer> numbers = new ArrayList<>(Arrays.asList(10, 25, 30, 45, 50));
    
            // Remove all numbers less than 30
            numbers.removeIf(n -> n < 30);
    
            System.out.println("After removeIf: " + numbers);
        }
    }
    

    Output

    After removeIf: [30, 45, 50]

    After using removeIf, the list contains only numbers greater than or equal to 30

  • How to Join a List of Strings with Custom Delimiter, Prefix, and Suffix Using Java 8 Streams

    βœ… Problem :

    How do you join a list of strings with a custom delimiter, prefix, and suffix using Java 8 Streams?

    βœ… Example:

    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class JoinStringsCustomDelimiter {
        public static void main(String[] args) {
            List<String> words = Arrays.asList("Apple", "Banana", "Grapes", "Blueberry");
    
            // Join strings with custom delimiter, prefix, and suffix
            String result = words.stream()
                .collect(Collectors.joining(", ", "[", "]"));
    
            System.out.println(result);
        }
    }
    

    βœ… Output:

    [Apple, Banana, Grapes, Blueberry]

    βœ… Explanation:

    1. words.stream(): Converts the list of strings into a Stream of String objects.
    2. Collectors.joining(“, “, “[“, “]”):
      • ", " is the delimiter between elements.
      • "[" is the prefix added at the beginning of the result.
      • "]" is the suffix added at the end of the result.
    3. The result is a single string with all words joined by the delimiter and wrapped in brackets.
    4. The output is printed using System.out.println().

  • Find the Sum of the First Two Elements in a List Using Java 8 Streams

    βœ… Problem :

    Using Java 8 Streams, how do you find the sum of the first two numbers in a list?

    βœ… Example:

    import java.util.Arrays;
    import java.util.List;
    
    public class SumOfFirstTwoNumbers {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(87, 45, 35, 74, 325);
    
            // Find sum of the first two numbers
            int sumOfTwoNumbers = numbers.stream()
                .limit(2)                      // Take only the first two elements
                .mapToInt(Integer::intValue)  // Convert Integer to int
                .sum();                       // Sum the elements
    
            System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);
        }
    }
    

    βœ… Output:

    Sum of first two numbers = 132
    

    (Since 87 + 45 = 132)


    βœ… Explanation:

    1. numbers.stream(): Converts the list of integers into a Stream of Integer objects.
    2. limit(2): Limits the stream to only the first two elements of the list.
    3. mapToInt(Integer::intValue): Converts each Integer object to primitive int for efficient summation.
    4. sum(): Calculates the sum of the remaining elements in the stream.
    5. Finally, the result is printed using System.out.println().
  • Find Words with Exactly ‘K’ Vowels in a Sentence in Java

    βœ… Correct Problem Sentence:

    Using Java 8 Streams, how do you extract all words from a sentence that contain exactly K vowels?

    βœ… Example:

    import java.util.Arrays;
    
    public class WordsWithVowels {
        public static void main(String[] args) {
            String sentence = "Why only half? Because we compare characters from both ends, no need to go full length.";
            int k = 3;  // Number of vowels to match in each word
    
            Arrays.stream(sentence.split("\\s+"))  // Split sentence into words
                .map(word -> word.replaceAll("[^a-zA-Z]", ""))  // Remove punctuation
                .filter(word -> countVowels(word) == k)         // Filter words with exactly k vowels
                .forEach(System.out::println);                 // Print each matching word
        }
    
        public static long countVowels(String word) {
            return word.chars()
                .mapToObj(ch -> (char) ch)
                .filter(ch -> "aeiouAEIOU".indexOf(ch) != -1)
                .count();
        }
    }
    

    βœ… Explanation:

    1. sentence.split(“\s+”): Splits the sentence by spaces into words.
    2. map(word -> word.replaceAll(“[^a-zA-Z]”, “”)): Removes punctuation (like ?, ., ,) from each word so only letters remain.
    3. filter(word -> countVowels(word) == k): Filters words where the number of vowels equals k (in this example, 3).
    4. forEach(System.out::println): Prints each word that satisfies the condition.
    5. The countVowels(String word) method:
      • Converts the word into a stream of characters (word.chars()).
      • Maps each int character code to a Character object.
      • Filters only vowels (case-insensitive).
      • Returns the count of vowels in the word.

    βœ… Sample Output (with k = 3):

    Because
    compare
    characters
    length

  • Sum of Unique Numbers in a List in Java

    Problem :

    How do you calculate the sum of only unique elements from a list using Java 8 Streams?

    βœ… Example:

    import java.util.Arrays;
    import java.util.List;
    
    public class SumOfUniqueNumbers {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(23, 45, 23, 15, 15, 78, 23, 85, 65);
    
            // Calculate sum of unique numbers
            int uniqueNumbersSum = numbers.stream()
                .distinct()                     // Get only unique elements
                .mapToInt(Integer::intValue)    // Convert Integer to int
                .sum();                         // Sum the unique numbers
    
            System.out.println("Sum of unique numbers: " + uniqueNumbersSum);
        }
    }
    

    βœ… Explanation:

    1. numbers.stream(): Creates a stream from the list of integers.
    2. distinct(): Removes duplicate elements from the stream, keeping only unique values.
    3. mapToInt(Integer::intValue): Converts Integer objects to primitive int for efficient processing.
    4. sum(): Computes the sum of the resulting IntStream.
    5. Finally, the result is printed with System.out.println().

    βœ… Output:

    Sum of unique numbers: 311
    

    Because the unique numbers are:

    23 + 45 + 15 + 78 + 85 + 65 = 311

  • Generate Summary Statistics of a List in Java 8

    Problem:

    Using Java 8 Streams, how do you quickly find minimum, maximum, sum, average, and count of numbers in a list without writing separate loops?

    βœ… Example:

    import java.util.Arrays;
    import java.util.IntSummaryStatistics;
    import java.util.List;
    
    public class SummaryStatisticsExample {
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(5, 3, 9, 1, 7);
    
            // Generate summary statistics
            IntSummaryStatistics stats = numbers.stream()
                .mapToInt(n -> n)  // Convert Integer to int
                .summaryStatistics();
    
            // Print results
            System.out.println("Minimum: " + stats.getMin());
            System.out.println("Maximum: " + stats.getMax());
            System.out.println("Sum: " + stats.getSum());
            System.out.println("Average: " + stats.getAverage());
            System.out.println("Count: " + stats.getCount());
        }
    }
    

    βœ… Explanation:

    1. numbers.stream(): Create a stream of integers from the list.
    2. mapToInt(n -> n): Converts the Stream<Integer> into an IntStream. This is necessary because IntSummaryStatistics works with primitive int.
    3. summaryStatistics(): This terminal operation generates an IntSummaryStatistics object, which contains:
      • Minimum value β†’ getMin()
      • Maximum value β†’ getMax()
      • Sum of all numbers β†’ getSum()
      • Average β†’ getAverage()
      • Count of elements β†’ getCount()
    4. The results are printed using System.out.println.

    βœ… Output:

    Minimum: 1
    Maximum: 9
    Sum: 25
    Average: 5.0
    Count: 5

  • Find the Sum of the First Two Elements in a List Using Java 8 Streams – Quick & Easy Example

    Problem:
    Using Java 8 Streams, how do you find the sum of the first two numbers in a list?

    βœ… Example:

    import java.util.Arrays;
    import java.util.List;
    
    public class SumOfFirstTwoNumbers {
    
        public static void main(String[] args) {
            List<Integer> numbers = Arrays.asList(87, 45, 35, 74, 325);
    
            int sumOfTwoNumbers = numbers.stream()
                    .limit(2)  // Take first two elements
                    .mapToInt(Integer::intValue)  // Convert to int stream
                    .sum();  // Calculate the sum
    
            System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);
        }
    }
    

    βœ… Output:

    Sum of first two numbers = 132

    βœ… Explanation:

    1. The list of numbers: [87, 45, 35, 74, 325]
    2. .stream() creates a stream of elements from the list.
    3. .limit(2) restricts the stream to the first two elements: [87, 45].
    4. .mapToInt(Integer::intValue) converts Integer to primitive int for summing.
    5. .sum() computes the sum of the two numbers:
      87 + 45 = 132.
    6. Finally, print the result: System.out.println("Sum of first two numbers = " + sumOfTwoNumbers);

  • Find the First Repeating Character in a String in Java

    Problem:
    Using Java 8 Streams, how do you find the first repeating character in a given string?

    βœ… Example:

    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class FindFirstRepeatingCharacter {
    
        public static void main(String[] args) {
            String input = "repeating-characters";
    
            input.chars()
                    .mapToObj(ch -> (char) ch)
                    .collect(Collectors.groupingBy(
                            ch -> ch,
                            LinkedHashMap::new,  // Preserve insertion order
                            Collectors.counting()))
                    .entrySet()
                    .stream()
                    .filter(entry -> entry.getValue() > 1)  // Find characters appearing more than once
                    .map(Map.Entry::getKey)
                    .findFirst()
                    .ifPresent(System.out::println);
        }
    }
    

    βœ… Output:

    e

    βœ… Explanation:

    1. Step 1 – Convert String to Character Stream: input.chars().mapToObj(ch -> (char) ch)
      • Converts the string "repeating-characters" to a stream of characters.
    2. Step 2 – Group by Character Count: .collect(Collectors.groupingBy( ch -> ch, LinkedHashMap::new, Collectors.counting()))
      • Creates a LinkedHashMap<Character, Long> where the key is the character and the value is the count of occurrences.
      • LinkedHashMap preserves the order of first appearance.
    3. Step 3 – Filter Repeating Characters: .filter(entry -> entry.getValue() > 1)
      • Keeps only characters that occur more than once.
    4. Step 4 – Pick First Repeating Character: .findFirst()
      • Finds the first character (in the original order) that repeats.
    5. Step 5 – Print the Character: ifPresent(System.out::println);