Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filtering negative values

Tags:

java

android

math

How to filter negative values from a set of arrays? I just want to get the positive values, is there any specific class to do it in Java? Is the Math.max in Java is the correct class to do it?

like image 371
Steven Pongidin Avatar asked Dec 30 '25 13:12

Steven Pongidin


2 Answers

Java 8+

You can use Stream and lambda expressions:

Integer[] numbers = {1, -5, 3, 2, -4, 7, 8};

Integer[] positives = Arrays.asList(numbers)
                            .stream()
                            .filter(i -> i > 0)        // >= to include 0
                            .toArray(Integer[]::new);

System.out.println(Arrays.asList(positives));

Output:

[1, 3, 2, 7, 8]
like image 128
ROMANIA_engineer Avatar answered Jan 02 '26 02:01

ROMANIA_engineer


Is the Math.max in Java is the correct class to do it?

Math is class and Math.max() is static method ,

You just simply need to check each element against the condition

if(number < 0 ){
   //negative
}
like image 24
jmj Avatar answered Jan 02 '26 04:01

jmj