Java
Array
Programming
Code Example
Negative Numbers

Removal of negative numbers from an array in Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Removing negative numbers from an array in Java sounds like an in-place operation, but arrays in Java have a fixed length. In practice, you create a new array containing only the values you want to keep.

The Stream-Based Solution

For int[], the cleanest modern approach is often an IntStream filter:

java
1import java.util.Arrays;
2
3public class Main {
4    public static void main(String[] args) {
5        int[] numbers = {4, -2, 7, -9, 0, 3};
6
7        int[] nonNegative = Arrays.stream(numbers)
8                .filter(n -> n >= 0)
9                .toArray();
10
11        System.out.println(Arrays.toString(nonNegative));
12    }
13}

Output:

text
[4, 7, 0, 3]

This is concise and expressive. It is also a good choice when the rest of the code already uses streams.

The Manual Loop Solution

If you want more control or need to avoid streams, use a loop. Since arrays are fixed-size, a common pattern is to collect the kept values in a list first, then copy them back into a new array.

java
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.List;
4
5public class Main {
6    public static void main(String[] args) {
7        int[] numbers = {4, -2, 7, -9, 0, 3};
8        List<Integer> kept = new ArrayList<>();
9
10        for (int n : numbers) {
11            if (n >= 0) {
12                kept.add(n);
13            }
14        }
15
16        int[] result = new int[kept.size()];
17        for (int i = 0; i < kept.size(); i++) {
18            result[i] = kept.get(i);
19        }
20
21        System.out.println(Arrays.toString(result));
22    }
23}

This version is longer, but it makes the resizing step explicit.

Why You Cannot Truly Remove From an Array

The phrase "remove from an array" is slightly misleading in Java. Arrays do not shrink. Once created, their length is fixed:

java
int[] numbers = {1, 2, 3};
System.out.println(numbers.length); // 3

Because of that, you must either:

  • create a new array
  • use a dynamic collection such as ArrayList<Integer>

If the data needs frequent insertions and removals, the second option is often a better model than repeatedly rebuilding arrays.

Keep Zero or Remove Zero

Most versions of this task want to remove only numbers below zero and keep zero. That means the predicate should be n >= 0.

If you want to remove zero too, change the condition:

java
int[] positiveOnly = Arrays.stream(numbers)
        .filter(n -> n > 0)
        .toArray();

Being explicit about the rule avoids ambiguity during maintenance.

Performance Notes

For ordinary application code, both the stream solution and the manual loop are fine. The right choice is usually readability. A manual loop may be easier to extend if you need extra logic, logging, or statistics while filtering.

The stream solution is attractive because it keeps the whole transformation in one place. It also avoids boxing because Arrays.stream(int[]) produces an IntStream, not a Stream<Integer>.

When a List Is Better Than an Array

If the collection size changes repeatedly, converting back to an array each time becomes awkward. In that case, work with a list directly:

java
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.List;
4
5List<Integer> values = new ArrayList<>(Arrays.asList(4, -2, 7, -9, 0, 3));
6values.removeIf(n -> n < 0);
7
8System.out.println(values); // [4, 7, 0, 3]

This does not operate on a primitive int[], but it is often the better design if true removals are part of the requirement.

Common Pitfalls

The most common mistake is trying to shrink the original array in place. Java arrays do not support that.

Another issue is using Stream<Integer> unnecessarily when IntStream from Arrays.stream(int[]) is simpler and avoids boxing overhead.

People also forget to define whether zero should remain. n >= 0 and n > 0 answer different requirements, so choose one deliberately.

Summary

  • Java arrays have fixed length, so removing negatives means building a new array.
  • 'Arrays.stream(numbers).filter(n -> n >= 0).toArray() is the cleanest solution for many cases.'
  • A manual loop is a good choice when you want explicit control.
  • Keep using a list instead of an array when the collection size changes often.
  • Decide clearly whether zero should stay or be removed with the negative values.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.