Java函数数组过滤:如何使用Java函数过滤数字数组中的负数?
发布时间:2023-07-04 22:09:40
在Java中,可以使用lambda表达式和流来过滤数字数组中的负数。
1. 创建一个整数数组,包含一些正数和负数。
int[] numbers = {1, -2, 3, -4, 5, -6, 7, 8, -9};
2. 使用lambda表达式和流来过滤负数。
int[] filteredNumbers = Arrays.stream(numbers)
.filter(num -> num >= 0)
.toArray();
这段代码首先将数组转换为流,然后使用filter方法过滤掉小于0的数值,最后使用toArray方法将过滤后的数字收集到一个新的数组中。
3. 打印过滤后的数组。
System.out.print("过滤后的数组: ");
for (int num : filteredNumbers) {
System.out.print(num + " ");
}
使用上述代码可以打印出过滤后的数组。
完整的代码如下:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {1, -2, 3, -4, 5, -6, 7, 8, -9};
int[] filteredNumbers = Arrays.stream(numbers)
.filter(num -> num >= 0)
.toArray();
System.out.print("过滤后的数组: ");
for (int num : filteredNumbers) {
System.out.print(num + " ");
}
}
}
以上是使用lambda表达式和流来过滤数字数组中的负数的方法。
