<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sivasankar Cherukuri on Medium]]></title>
        <description><![CDATA[Stories by Sivasankar Cherukuri on Medium]]></description>
        <link>https://medium.com/@cherukurisankar?source=rss-46c04a6dcfbd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*loGVKMTsYFJgs4h2kFfJoA.jpeg</url>
            <title>Stories by Sivasankar Cherukuri on Medium</title>
            <link>https://medium.com/@cherukurisankar?source=rss-46c04a6dcfbd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:03:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cherukurisankar/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LeetCode Problem #1 — Longest Substring Without Repeating Characters” in Java: From Brute Force to…]]></title>
            <link>https://medium.com/@cherukurisankar/leetcode-problem-1-longest-substring-without-repeating-characters-in-java-from-brute-force-to-161d013eb70c?source=rss-46c04a6dcfbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/161d013eb70c</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[leetcode-medium]]></category>
            <category><![CDATA[sliding-windows]]></category>
            <dc:creator><![CDATA[Sivasankar Cherukuri]]></dc:creator>
            <pubDate>Fri, 12 Dec 2025 23:33:28 GMT</pubDate>
            <atom:updated>2025-12-12T23:33:28.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>LeetCode Problem #1 — Longest Substring Without Repeating Characters” in Java: From Brute Force to Optimal Solutions</h3><h3>Introduction</h3><p>The “Longest Substring Without Repeating Characters” problem is a classic coding challenge that frequently appears in technical interviews at top tech companies like Google, Amazon, Facebook, and Microsoft. It’s a perfect problem to test your understanding of string manipulation, hash-based data structures, and the powerful sliding window technique.</p><p><strong>Problem Statement:</strong></p><p>Given a string s, find the length of the longest substring without repeating characters.</p><p><strong>Examples:</strong></p><ul><li>Input: s = &quot;abcabcbb&quot; → Output: 3 (The answer is &quot;abc&quot;)</li><li>Input: s = &quot;bbbbb&quot; → Output: 1 (The answer is &quot;b&quot;)</li><li>Input: s = &quot;pwwkew&quot; → Output: 3 (The answer is &quot;wke&quot;)</li></ul><p><strong>Why This Problem Matters:</strong></p><p>This problem is important because it tests several key concepts:</p><ol><li><strong>Pattern Recognition</strong>: Identifying when to use the sliding window technique</li><li><strong>Data Structure Selection</strong>: Choosing between HashSet, HashMap, or arrays</li><li><strong>Optimization Skills</strong>: Moving from brute force to optimal solutions</li><li><strong>Edge Case Handling</strong>: Dealing with empty strings, single characters, and all unique characters</li></ol><p>Let’s explore all the possible approaches to solve this problem, from the most intuitive to the most optimized.</p><h3>Solution 1: Brute Force Approach</h3><h3>The Concept</h3><p>The brute force approach is straightforward: check every possible substring and determine if it has all unique characters. Keep track of the maximum length found.</p><h3>Algorithm Steps</h3><ol><li>Generate all possible substrings using two nested loops</li><li>For each substring, check if all characters are unique</li><li>If unique, update the maximum length</li><li>Return the maximum length</li></ol><h3>Java Implementation</h3><pre>public class Solution {<br>    public int lengthOfLongestSubstring(String s) {<br>        int n = s.length();<br>        int maxLength = 0;<br>        <br>        // Iterate through all possible starting positions<br>        for (int i = 0; i &lt; n; i++) {<br>            // For each starting position, try all possible ending positions<br>            for (int j = i; j &lt; n; j++) {<br>                // Check if substring from i to j has all unique characters<br>                if (allUnique(s, i, j)) {<br>                    maxLength = Math.max(maxLength, j - i + 1);<br>                }<br>            }<br>        }<br>        <br>        return maxLength;<br>    }<br>    <br>    /**<br>     * Helper method to check if all characters in substring s[start...end] are unique<br>     * Uses a HashSet to track seen characters<br>     */<br>    private boolean allUnique(String s, int start, int end) {<br>        Set&lt;Character&gt; set = new HashSet&lt;&gt;();<br>        <br>        for (int i = start; i &lt;= end; i++) {<br>            char c = s.charAt(i);<br>            // If character already exists in set, we have a duplicate<br>            if (set.contains(c)) {<br>                return false;<br>            }<br>            set.add(c);<br>        }<br>        <br>        return true;<br>    }<br>}</pre><h3>Complexity Analysis</h3><p><strong>Time Complexity: O(n³)</strong></p><ul><li>Outer loop: O(n)</li><li>Inner loop: O(n)</li><li>allUnique method: O(n) in worst case</li><li>Total: O(n) × O(n) × O(n) = O(n³)</li></ul><p><strong>Space Complexity: O(min(n, m))</strong></p><ul><li>Where n is the length of the string and m is the charset size</li><li>The HashSet in allUnique can have at most min(n, m) characters</li></ul><h3>When to Use This Approach</h3><ul><li><strong>Never in production code</strong> — This is purely for understanding the problem</li><li>Useful for explaining your thought process in interviews before optimizing</li><li>Good starting point to demonstrate problem-solving progression</li></ul><h3>Solution 2: Sliding Window with HashSet</h3><h3>The Concept</h3><p>The sliding window technique is a game-changer for this problem. Instead of checking every substring, we maintain a window of unique characters and slide it through the string. When we encounter a duplicate, we shrink the window from the left until the duplicate is removed.</p><h3>Algorithm Steps</h3><ol><li>Use two pointers: left (start of window) and right (end of window)</li><li>Use a HashSet to track characters in the current window</li><li>Expand the window by moving right pointer</li><li>If we encounter a duplicate, shrink the window by moving left pointer</li><li>Track the maximum window size seen</li></ol><h3>Java Implementation</h3><pre>public class Solution {<br>    public int lengthOfLongestSubstring(String s) {<br>        int n = s.length();<br>        Set&lt;Character&gt; set = new HashSet&lt;&gt;();<br>        int maxLength = 0;<br>        int left = 0; // Left pointer of the sliding window<br>        <br>        // Right pointer expands the window<br>        for (int right = 0; right &lt; n; right++) {<br>            char currentChar = s.charAt(right);<br>            <br>            // If character is already in set, shrink window from left<br>            // Keep removing characters until the duplicate is gone<br>            while (set.contains(currentChar)) {<br>                set.remove(s.charAt(left));<br>                left++; // Move left pointer forward<br>            }<br>            <br>            // Add current character to the set<br>            set.add(currentChar);<br>            <br>            // Update maximum length<br>            // Current window size is (right - left + 1)<br>            maxLength = Math.max(maxLength, right - left + 1);<br>        }<br>        <br>        return maxLength;<br>    }<br>}</pre><h3>Complexity Analysis</h3><p><strong>Time Complexity: O(2n) = O(n)</strong></p><ul><li>In the worst case, each character will be visited twice: once by right pointer and once by left pointer</li><li>Example: “abcdefga” — when we reach the second ‘a’, we remove ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’</li></ul><p><strong>Space Complexity: O(min(n, m))</strong></p><ul><li>HashSet stores at most min(n, m) characters</li><li>Where n is string length and m is charset size (128 for ASCII, 256 for extended ASCII)</li></ul><h3>Why This Works</h3><p>The key insight is that if substring s[i:j] has all unique characters, and we want to extend it to s[i:j+1], we only need to check if s[j+1] is already in the substring. If it is, we know that any substring starting before the first occurrence of s[j+1] will also have a duplicate, so we can skip all of them.</p><h3>Solution 3: Optimized Sliding Window with HashMap</h3><h3>The Concept</h3><p>This is an enhancement of the HashSet approach. Instead of removing characters one by one when we find a duplicate, we can jump the left pointer directly to the position after the last occurrence of the duplicate character. We use a HashMap to store the index of each character’s most recent occurrence.</p><h3>Algorithm Steps</h3><ol><li>Use a HashMap to store character → index mapping</li><li>Use left pointer to mark the start of the current window</li><li>When we find a duplicate, jump left to max(left, lastIndex + 1)</li><li>Update the character’s index in the map</li><li>Track the maximum window size</li></ol><h3>Java Implementation</h3><pre>public class Solution {<br>    public int lengthOfLongestSubstring(String s) {<br>        int n = s.length();<br>        Map&lt;Character, Integer&gt; map = new HashMap&lt;&gt;();<br>        int maxLength = 0;<br>        int left = 0; // Start of current window<br>        <br>        for (int right = 0; right &lt; n; right++) {<br>            char currentChar = s.charAt(right);<br>            <br>            // If character exists in map and its index is within current window<br>            if (map.containsKey(currentChar)) {<br>                // Move left pointer to position after last occurrence<br>                // Use Math.max to ensure left never moves backwards<br>                left = Math.max(left, map.get(currentChar) + 1);<br>            }<br>            <br>            // Update the character&#39;s most recent index<br>            map.put(currentChar, right);<br>            <br>            // Update maximum length<br>            maxLength = Math.max(maxLength, right - left + 1);<br>        }<br>        <br>        return maxLength;<br>    }<br>}</pre><h3>Complexity Analysis</h3><p><strong>Time Complexity: O(n)</strong></p><ul><li>Single pass through the string</li><li>Each character is visited exactly once by the right pointer</li><li>HashMap operations (get, put, containsKey) are O(1) on average</li></ul><p><strong>Space Complexity: O(min(n, m))</strong></p><ul><li>HashMap stores at most min(n, m) entries</li><li>Where n is string length and m is charset size</li></ul><h3>Why This Is Better</h3><p>The key optimization is the Math.max(left, map.get(currentChar) + 1) line. Consider the string &quot;abba&quot;:</p><ul><li>When we’re at index 2 (second ‘b’), we find ‘b’ at index 1</li><li>We set left = max(0, 1+1) = 2</li><li>When we’re at index 3 (second ‘a’), we find ‘a’ at index 0</li><li>We set left = max(2, 0+1) = 2 (doesn&#39;t move backwards!)</li></ul><p>This prevents the left pointer from moving backwards when we encounter characters that were seen before the current window.</p><h3>Solution 4: Array-Based Sliding Window (Most Optimized)</h3><h3>The Concept</h3><p>If we know the character set is limited (like ASCII), we can use an integer array instead of a HashMap. This provides true O(1) lookup time and is more cache-efficient.</p><h3>Algorithm Steps</h3><p>Same as HashMap approach, but using an array indexed by character ASCII value.</p><h3>Java Implementation</h3><pre>public class Solution {<br>    public int lengthOfLongestSubstring(String s) {<br>        int n = s.length();<br>        int maxLength = 0;<br>        int left = 0;<br>        <br>        // Array to store the last seen index of each character<br>        // Initialize with -1 to indicate character not seen<br>        // Assuming ASCII charset (128 characters)<br>        int[] lastSeen = new int[128];<br>        Arrays.fill(lastSeen, -1);<br>        <br>        for (int right = 0; right &lt; n; right++) {<br>            char currentChar = s.charAt(right);<br>            <br>            // If character was seen and is in current window<br>            if (lastSeen[currentChar] &gt;= left) {<br>                // Move left pointer to position after last occurrence<br>                left = lastSeen[currentChar] + 1;<br>            }<br>            <br>            // Update character&#39;s last seen index<br>            lastSeen[currentChar] = right;<br>            <br>            // Update maximum length<br>            maxLength = Math.max(maxLength, right - left + 1);<br>        }<br>        <br>        return maxLength;<br>    }<br>}</pre><h3>For Extended ASCII or Unicode</h3><pre>public class Solution {<br>    public int lengthOfLongestSubstring(String s) {<br>        int n = s.length();<br>        int maxLength = 0;<br>        int left = 0;<br>        <br>        // For extended ASCII (256 characters)<br>        int[] lastSeen = new int[256];<br>        Arrays.fill(lastSeen, -1);<br>        <br>        for (int right = 0; right &lt; n; right++) {<br>            char currentChar = s.charAt(right);<br>            <br>            if (lastSeen[currentChar] &gt;= left) {<br>                left = lastSeen[currentChar] + 1;<br>            }<br>            <br>            lastSeen[currentChar] = right;<br>            maxLength = Math.max(maxLength, right - left + 1);<br>        }<br>        <br>        return maxLength;<br>    }<br>}</pre><h3>Complexity Analysis</h3><p><strong>Time Complexity: O(n)</strong></p><ul><li>Single pass through the string</li><li>Array access is true O(1) (not amortized like HashMap)</li></ul><p><strong>Space Complexity: O(m)</strong></p><ul><li>Where m is the charset size (128 for ASCII, 256 for extended ASCII)</li><li>Fixed space regardless of input string length</li></ul><h3>When to Use This Approach</h3><ul><li><strong>Best for ASCII or limited character sets</strong></li><li>Faster than HashMap due to no hashing overhead</li><li>More cache-friendly</li><li>Not suitable for Unicode strings with large character ranges</li></ul><h3>Comprehensive Comparison</h3><h3>Time Complexity Summary</h3><p>Approach Time Complexity Space Complexity Pass Count Brute Force O(n³) O(min(n, m)) Multiple nested Sliding Window (HashSet) O(2n) = O(n) O(min(n, m)) Up to 2 passes Sliding Window (HashMap) O(n) O(min(n, m)) Single pass Array-Based Sliding Window O(n) O(m) Single pass</p><h3>Performance Comparison</h3><p><strong>For string “abcabcbb” (length = 8):</strong></p><ol><li><strong>Brute Force</strong>:</li></ol><ul><li>Checks 36 substrings (8 + 7 + 6 + 5 + 4 + 3 + 2 + 1)</li><li>Each check involves iterating through characters</li><li>~200+ operations</li></ul><p><strong>2. HashSet Sliding Window</strong>:</p><ul><li>Right pointer: 8 iterations</li><li>Left pointer: moves 6 times total</li><li>~14 operations</li></ul><p><strong>3. HashMap Sliding Window</strong>:</p><ul><li>Right pointer: 8 iterations</li><li>Left pointer: jumps directly (no intermediate removals)</li><li>~8 operations</li></ul><p><strong>4. Array-Based</strong>:</p><ul><li>8 iterations with fastest lookup</li><li>~8 operations with better cache performance</li></ul><h3>When to Use Each Approach</h3><p><strong>Brute Force:</strong></p><ul><li>Never in production</li><li>Only for explaining thought process</li><li>Teaching basic concepts</li></ul><p><strong>HashSet Sliding Window:</strong></p><ul><li>Good for interviews when you want to show progression</li><li>When you need to actually track the characters in the window</li><li>Easier to understand and explain</li></ul><p><strong>HashMap Sliding Window:</strong></p><ul><li>Best general-purpose solution</li><li>Works with any character set (including Unicode)</li><li>Optimal for dynamic or unknown character sets</li><li><strong>Recommended for most interview scenarios</strong></li></ul><p><strong>Array-Based Sliding Window:</strong></p><ul><li>Best when character set is known and limited (ASCII)</li><li>Highest performance for production code</li><li>Good for competitive programming</li><li>Use when space for fixed array is acceptable</li></ul><h3>Common Mistakes to Avoid</h3><h3>1. Forgetting Edge Cases</h3><pre>// Don&#39;t forget to handle:<br>String s1 = &quot;&quot;;          // Empty string → return 0<br>String s2 = &quot;a&quot;;         // Single character → return 1<br>String s3 = &quot;aab&quot;;       // Duplicate at end<br>String s4 = &quot;abcdefg&quot;;   // All unique → return length</pre><h3>2. Off-by-One Errors</h3><pre>// ❌ Wrong: window size calculation<br>int size = right - left; // Missing the +1</pre><pre>// ✅ Correct:<br>int size = right - left + 1;</pre><h3>3. Not Using Math.max for left Pointer</h3><pre>// ❌ Wrong: left pointer can move backwards<br>if (map.containsKey(currentChar)) {<br>    left = map.get(currentChar) + 1;<br>}</pre><pre>// ✅ Correct: prevents moving backwards<br>if (map.containsKey(currentChar)) {<br>    left = Math.max(left, map.get(currentChar) + 1);<br>}</pre><h3>4. Modifying Map Before Checking</h3><pre>// ❌ Wrong: updates map before checking<br>map.put(currentChar, right);<br>if (map.containsKey(currentChar)) { // Will always be true!<br>    // ...<br>}</pre><pre>// ✅ Correct: check first, then update<br>if (map.containsKey(currentChar)) {<br>    left = Math.max(left, map.get(currentChar) + 1);<br>}<br>map.put(currentChar, right);</pre><h3>5. Not Initializing Array Properly</h3><pre>// ❌ Wrong: default 0 values cause issues<br>int[] lastSeen = new int[128];<br>// 0 is a valid index!</pre><pre>// ✅ Correct: initialize with -1<br>int[] lastSeen = new int[128];<br>Arrays.fill(lastSeen, -1);</pre><h3>Practical Tips for Mastering This Problem</h3><h3>1. Visualize the Sliding Window</h3><p>Draw out the process for “abcabcbb”:</p><pre>a b c a b c b b<br>^                left=0, right=0, len=1, set={a}<br>  ^              left=0, right=1, len=2, set={a,b}<br>    ^            left=0, right=2, len=3, set={a,b,c}<br>      ^          left=1, right=3, len=3, set={b,c,a}<br>        ^        left=2, right=4, len=3, set={c,a,b}<br>          ^      left=3, right=5, len=3, set={a,b,c}<br>            ^    left=4, right=6, len=3, set={b,c}<br>              ^  left=5, right=7, len=3, set={c,b}</pre><h3>2. Practice Related Problems</h3><ul><li>Longest Substring with At Most K Distinct Characters</li><li>Minimum Window Substring</li><li>Permutation in String</li><li>Find All Anagrams in a String</li></ul><h3>3. Interview Strategy</h3><p><strong>Step-by-step approach:</strong></p><ol><li>Start by explaining the brute force (1–2 minutes)</li><li>Identify why it’s inefficient</li><li>Introduce sliding window concept</li><li>Code the HashMap solution (most versatile)</li><li>If time permits, mention the array optimization</li></ol><p><strong>What to say:</strong></p><blockquote><em>“I’ll start with a brute force approach to make sure we’re on the same page, then optimize to a sliding window solution which is more efficient.”</em></blockquote><h3>4. Time Management</h3><ul><li>Brute force explanation: 2 minutes</li><li>Optimal solution coding: 10–15 minutes</li><li>Testing and edge cases: 5 minutes</li><li>Complexity analysis: 2–3 minutes</li></ul><h3>5. Key Insights to Mention</h3><ul><li>“This is a classic sliding window problem”</li><li>“We maintain a window with all unique characters”</li><li>“When we find a duplicate, we shrink from the left”</li><li>“HashMap allows us to jump directly to the right position”</li></ul><h3>Complete Test Suite</h3><pre>public class SolutionTest {<br>    public static void main(String[] args) {<br>        Solution solution = new Solution();<br>        <br>        // Test case 1: Example from problem<br>        assert solution.lengthOfLongestSubstring(&quot;abcabcbb&quot;) == 3 : &quot;Test 1 failed&quot;;<br>        <br>        // Test case 2: All same characters<br>        assert solution.lengthOfLongestSubstring(&quot;bbbbb&quot;) == 1 : &quot;Test 2 failed&quot;;<br>        <br>        // Test case 3: Example from problem<br>        assert solution.lengthOfLongestSubstring(&quot;pwwkew&quot;) == 3 : &quot;Test 3 failed&quot;;<br>        <br>        // Test case 4: Empty string<br>        assert solution.lengthOfLongestSubstring(&quot;&quot;) == 0 : &quot;Test 4 failed&quot;;<br>        <br>        // Test case 5: Single character<br>        assert solution.lengthOfLongestSubstring(&quot;a&quot;) == 1 : &quot;Test 5 failed&quot;;<br>        <br>        // Test case 6: All unique characters<br>        assert solution.lengthOfLongestSubstring(&quot;abcdef&quot;) == 6 : &quot;Test 6 failed&quot;;<br>        <br>        // Test case 7: Duplicate at end<br>        assert solution.lengthOfLongestSubstring(&quot;abcdefa&quot;) == 6 : &quot;Test 7 failed&quot;;<br>        <br>        // Test case 8: Two characters<br>        assert solution.lengthOfLongestSubstring(&quot;au&quot;) == 2 : &quot;Test 8 failed&quot;;<br>        <br>        // Test case 9: Pattern with space<br>        assert solution.lengthOfLongestSubstring(&quot;a b c&quot;) == 3 : &quot;Test 9 failed&quot;;<br>        <br>        System.out.println(&quot;All tests passed!&quot;);<br>    }<br>}</pre><h3>Conclusion</h3><p>The “Longest Substring Without Repeating Characters” problem is an excellent demonstration of how the right technique and data structure can transform an O(n³) solution into an O(n) solution. The sliding window pattern is powerful and appears in many string and array problems.</p><p><strong>Key Takeaways:</strong></p><ol><li><strong>Always consider sliding window</strong> for substring/subarray problems</li><li><strong>Choose the right data structure</strong>: HashMap for flexibility, array for performance</li><li><strong>Optimize incrementally</strong>: Start simple, then improve</li><li><strong>Handle edge cases</strong>: Empty strings, single characters, all unique</li><li><strong>Practice visualization</strong>: Draw the window movement on paper</li></ol><p><strong>Recommended Next Steps:</strong></p><ul><li>Implement all four solutions yourself</li><li>Test with various inputs</li><li>Practice explaining your approach out loud</li><li>Solve related sliding window problems</li><li>Time yourself to improve speed</li></ul><p>Remember, in interviews, demonstrating your thought process and ability to optimize is often more important than immediately arriving at the optimal solution. Good luck with your coding journey!</p><p><em>Found this helpful? Follow me for more in-depth problem-solving guides and coding interview tips!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=161d013eb70c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be Careful with Stream.toList() in Java]]></title>
            <link>https://medium.com/@cherukurisankar/be-careful-with-stream-tolist-in-java-bd50e83addde?source=rss-46c04a6dcfbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd50e83addde</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Sivasankar Cherukuri]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 11:14:01 GMT</pubDate>
            <atom:updated>2024-06-07T11:19:22.845Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Be Careful with Stream.toList() in Java</strong></p><p>In Java, the `Stream` interface provides a `toList()` method and the `Collectors` class provides a `toList()` method. Both methods are used to collect the elements of a stream into a list, but they return different types of lists.</p><p><strong>Stream’s toList() method</strong>: This method was introduced in Java 16. It collects the elements of the stream into an unmodifiable list. An unmodifiable list is a list that does not support any operation that modifies its elements or its size. This includes methods like `add()`, `remove()`, and `set()`. If you try to call any of these methods on an unmodifiable list, it will throw an `UnsupportedOperationException`.</p><p>Here’s an example of using Stream’s `toList()` method:</p><pre>List&lt;String&gt; list = Stream.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;).toList();</pre><p><strong>Collectors’ toList() method:</strong> This method collects the elements of the stream into a `List` implementation that supports all list operations, including those that modify the list. By default, it returns an `ArrayList`, but this is an implementation detail and not guaranteed by the specification.</p><p>Here’s an example of using the Collectors’ `toList()` method:</p><pre>List&lt;String&gt; list = Stream.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;).collect(Collectors.toList());</pre><p>In general, you should use Stream’s `toList()` method when you don’t need to modify the list after it’s created, and Collectors’ `toList()` method when you do need to modify the list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd50e83addde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StringJoiners in Java 8]]></title>
            <link>https://medium.com/@cherukurisankar/stringjoiners-in-java-8-e1e97c195e32?source=rss-46c04a6dcfbd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1e97c195e32</guid>
            <category><![CDATA[string]]></category>
            <category><![CDATA[java8]]></category>
            <dc:creator><![CDATA[Sivasankar Cherukuri]]></dc:creator>
            <pubDate>Fri, 24 Sep 2021 09:59:32 GMT</pubDate>
            <atom:updated>2024-06-04T05:57:44.870Z</atom:updated>
            <content:encoded><![CDATA[<h3>Different ways to join the strings in Java</h3><p>Joining strings is very common in day-to-day programming, provided you have an array or list of things. Let’s say you wish to build another string with capital letters by joining “January”, “February”, “March”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”. The months of the year are “JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER” There is also no simple way to implement it in Java. Let’s explore what we can do programmatically with this.</p><pre>List&lt;String&gt; months = Arrays.asList(&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;);<br>for (String month : months) {<br>   System.out.print(month + &quot;, &quot;);<br>}</pre><blockquote>Output: January, February, March, April, May, June, July, August, September, October, November, December,</blockquote><p>If you look closely, there is one foolish comma in the output of the above program. We must loop through an array or list, appending a comma after each element with a StringBuilder, and then removing the last comma because we don’t want a comma after the last element.</p><pre>import java.util.Arrays;<br>import java.util.List;<br><br>public class Manager {<br><br> public static String join(List list, String delimeter) {<br>  StringBuilder builder = new StringBuilder();<br>  boolean firstPosition = true;<br>  for (Object item : list) {<br>   if (firstPosition) {<br>    firstPosition = false;<br>   } else {<br>    builder.append(delimeter);<br>   }<br>   builder.append(item.toString().toUpperCase());<br>  }<br> return builder.toString();<br>}<br><br> public static void main(String[] args) {<br>  List months = Arrays.asList(&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, <br>  &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;,&quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;);<br>  System.out.println(join(months, &quot;,&quot;));<br> }<br>}</pre><p><em>Output: JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER</em></p><p>Like Javascript Array.join() we don&#39;t have any readymade API in Java before Java 8. We must depend on 3rd party APIs like Apache Commons, and Google Guava. Before going to discuss the Java 8 join method and String. join method will see a few examples with Apache Commons and Guava.</p><h4>Apache commons StringUtils.join() method:</h4><pre>List months = Arrays.asList(&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;,&quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;);<br>System.out.println(StringUtils.join(months, &quot;|&quot;));</pre><p>Output:<strong>January|February|March|April|May|June|July|August|September|October|November|December</strong></p><p>For more details about the StringUtils.join() method, I’d recommend taking a closer look: <a href="http://commons.apache.org/lang/api-3.1/org/apache/commons/lang3/StringUtils.html">Click Here</a></p><h4>Guava Joiner :</h4><pre>List months = Arrays.asList(&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;);<br>System.out.println(Joiner.on(&quot;,&quot;).join(months));</pre><p>For more details about Guava Joiner I’d recommend taking a closer look: <a href="https://google.github.io/guava/releases/16.0/api/docs/index.html?com/google/common/base/Joiner.html">Click Here</a></p><h4>How to use String.join() method:</h4><p>There are two overloaded join methods in the String class,</p><pre>public static String join(CharSequence delimiter,CharSequence... elements)<br>Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.<br>For example,<br> String message = String.join(&quot;-&quot;, &quot;Java&quot;, &quot;is&quot;, &quot;cool&quot;); // message returned is: &quot;Java-is-cool&quot;<br>Note that if an element is null, then &quot;null&quot; is added.<br>Parameters:<br>delimiter - the delimiter that separates each element<br>elements - the elements to join together.<br>Returns: a new String that is composed of the elements separated by the delimiter<br>Throws: NullPointerException - If delimiter or elements is null<br><br>public static String join(CharSequence delimiter, Iterable elements)<br>Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.<br>For example,<br> List strings = List.of(&quot;Java&quot;, &quot;is&quot;, &quot;cool&quot;);<br> String message = String.join(&quot; &quot;, strings); //message returned is: &quot;Java is cool&quot;<br> Set strings = new LinkedHashSet&lt;&gt;(List.of(&quot;Java&quot;, &quot;is&quot;, &quot;very&quot;, &quot;cool&quot;));<br> String message = String.join(&quot;-&quot;, strings);//message returned is: &quot;Java-is-very-cool&quot;<br>Note that if an individual element is null, then &quot;null&quot; is added.<br>Parameters:<br>delimiter - a sequence of characters that is used to separate each of the elements in the resulting String<br>elements - an Iterable that will have its elements joined together.<br>Returns: a new String that is composed from the elements argument<br>Throws: NullPointerException - If delimiter or elements is null</pre><p>Let’s see the Example for the String. join() method</p><pre>String join = String.join(&quot;|&quot;, &quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;, &quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;);<br>System.out.println(join);<br>List months = Arrays.asList(&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;,&quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;,&quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;);<br>String joiner = String.join(&quot;,&quot;, months);<br>System.out.println(joiner);</pre><p><strong>Output:</strong><br><strong>January|February|March|April|May|June|July|August|September|October|November|December</strong><br><strong>January,February,March,April,May,June,July,August,September,October,November,December</strong></p><h4>How to use StringJoiner class in Java:</h4><p>StringJoiner is part of java.util package.it is available from Java 8 onwards.</p><p>Here is what the new Java class says <a href="http://download.java.net/java/jdk9/docs/api/index.html?overview-summary.html">Here</a>.</p><p>StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.<br>There are two constructors available from the StringJoiner class</p><pre>public StringJoiner(CharSequence delimiter)<br>public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)</pre><p>One is taking delimiter and the other one allows prefix and suffix values.</p><pre>StringJoiner joiner = new StringJoiner(&quot;,&quot;);<br>String join = joiner.add(&quot;January&quot;).add(&quot;February&quot;).add(&quot;March&quot;).add(&quot;April&quot;).add(&quot;May&quot;).toString();<br>System.out.println(join);</pre><p>Output: January,February,March,April,May</p><pre>StringJoiner joiner = new StringJoiner(&quot;,&quot;,&quot;[&quot;,&quot;]&quot;);<br>String join = joiner.add(&quot;January&quot;)<br>                    .add(&quot;February&quot;)<br>                    .add(&quot;March&quot;)<br>                    .add(&quot;April&quot;)<br>                    .add(&quot;May&quot;)<br>                    .toString();<br>System.out.println(join);</pre><p>Output : [January,February,March,April,May]<br>Let&#39;s look at the StringJoiner methods once</p><pre>public StringJoiner add(CharSequence newElement)<br>public StringJoiner merge(StringJoiner other)<br>public int length()<br>public String toString()<br>public StringJoiner setEmptyValue(CharSequence emptyValue)</pre><p>But the real missing thing from the StringJoiner is a method to add multiple elements at once to the joiner. Whenever I want to join, I have a list, set,or Iterable StringUtils from the commons-lang, Guava, or String.join() separate methods. But it needs to be added to the StringJoiner.</p><pre>String join = String.join(&quot;, &quot;, list);<br>String join = Joiner.on(&quot;, &quot;).join(list);<br>String join = StringUtils.join(list,&quot;,&quot;)</pre><p>StringJoiner has no equivalent method. You have to add the elements individually using add(CharSequence)!</p><pre>StringJoiner joiner = new StringJoiner(&quot;, &quot;);<br> for (String str : list) {<br>   joiner.add(str);<br> }<br>String join = joiner.toString();</pre><h4>Another reason to use lambdas to join strings in Java 8:</h4><pre>List months = Arrays.asList(&quot;January&quot;, &quot;February&quot;, &quot;March&quot;, &quot;April&quot;,&quot;May&quot;, &quot;June&quot;, &quot;July&quot;, &quot;August&quot;, &quot;September&quot;, &quot;October&quot;, &quot;November&quot;, &quot;December&quot;);<br>String join = months.stream()<br>                    .map(String::toUpperCase)<br>                    .collect(Collectors.joining(&quot;, &quot;));<br>System.out.println(join);</pre><p>Output:<strong> JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER</strong></p><p>This concludes our discussion of StringJoiner and String in Java 8. If you don’t have Java 8, you can accomplish the same thing with third-party APIs such as Guava or Apache commons-lang (StringUtils.join). Please update your comments below if you discover new ways to join the string.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1e97c195e32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>