Moving Zeros to End with Java Streams

🚀 Moving Zeros to the End Using Java Streams I recently solved the classic “move zeros to the end” problem using a Java Streams approach, a bit different from the traditional two-pointer technique. The goal is simple: 👉 Move all zeros to the end 👉 Maintain the order of non-zero elements 🔹 Approach 1. Used Stream.concat() to concatenate two streams: 2. First stream, filters all non-zero elements 3. Second stream, filters all zero elements 4. Finally, collect the combined stream into a List. 💻 I’ve added my Java solution in the comments below. #Java #Java8 #Streams #Arrays #ProblemSolving #Coding

  • text

public class MoveZerosUsingStreams { public static void main(String[] args) { // Using int[] Array int[] nums = { 0, 4, 0, 1, 2, 0, 5, 55, 0, 9, 2 }; List<Integer> arrayApproach = Stream.concat(Arrays.stream(nums).boxed().filter(e -> e != 0), Arrays.stream(nums).boxed().filter(e -> e == 0)).collect(Collectors.toList()); System.out.println(arrayApproach); // Using List<Integer> List<Integer> list = List.of(0, 4, 0, 1, 2, 0, 5, 55, 0, 9, 2); List<Integer> listApproach = Stream.concat(list.stream().filter(e -> e != 0), list.stream().filter(e -> e == 0)) .collect(Collectors.toList()); System.out.println(listApproach); } }

Like
Reply

We can use “Collectors.partitioningBy” also: // For Array (input array -> int[ ] nums) Map<Boolean, List<Integer>> partitioned = Arrays.stream(nums).boxed().collect(Collectors.partitioningBy(n -> n == 0)); int[] result = Stream.concat(partitioned.get(false).stream(), partitioned.get(true).stream()).mapToInt(Integer::intValue).toArray(); System.out.println(Arrays.toString(result)); ——————————————————— // For list (Input List -> List<Integer> nums) Map<Boolean, List<Integer>> partitioned = nums.stream().collect(Collectors.partitioningBy(n -> n == 0)); List<Integer> result = Stream.concat(partitioned.get(false).stream(), partitioned.get(true).stream()).collect(Collectors.toList()); System.out.println(result);

Nice functional approach 👌 One observation, since we’re filtering twice and creating a new list, this becomes a multi-pass solution with O(n) extra space. In performance-critical scenarios, a single-pass two-pointer approach might be more optimal. Still, great demonstration of Streams Suresh Gudibanda

Hi C++ developer here couldn't understand the code but curious to know what was happening. What's the time complexity ? Is this a kind of sliding window concept?

output : [4, 1, 2, 5, 55, 9, 2, 0, 0, 0, 0] [4, 1, 2, 5, 55, 9, 2, 0, 0, 0, 0] for both approaches .Good solution.

See more comments

To view or add a comment, sign in

Explore content categories