Java 数组中删除空数据有四种方法:使用 Arrays.stream() 和 filter() 过滤出非空元素。使用 List.of() 和 removeAll() 将空元素添加到新列表中,然后从原始列表中删除。使用 Stream.concat() 和 Stream.of() 将空元素流连接到原始数组流,再过滤出非空元素。使用循环遍历数组,将非空元素添加到新数组中。
Java 数组中删除空数据
在 Java 数组中删除空数据有多种方法,以下是其中一些常用方法:
1. 使用 Arrays.stream() 和 filter()
int[] arr = {1, 2, 0, 4, 5, 0, 7};
// 使用 Arrays.stream(
) 创建流
IntStream stream = Arrays.stream(arr);
// 使用 filter() 过滤出不为 0 的元素
IntStream filteredStream = stream.filter(n -> n != 0);
// 将过滤后的流转换为数组
int[] newArr = filteredStream.toArray();2. 使用 List.of() 和 removeAll()
Listlist = List.of(1, 2, 0, 4, 5, 0, 7); // 将列表中的所有空数据 (0) 添加到新列表 List zeros = List.of(0); // 从列表中删除 newZeros 中的所有元素 list.removeAll(zeros); // 将列表转换为数组 int[] newArr = list.stream().mapToInt(i -> i).toArray();
3. 使用 Stream.concat() 和 Stream.of()
int[] arr = {1, 2, 0, 4, 5, 0, 7};
// 为所有空数据 (0) 创建一个包含 0 的流
Stream zeroStream = Stream.of(0);
// 将两个流连接在一起
Stream combinedStream = Stream.concat(Arrays.stream(arr), zeroStream);
// 过滤出不为 0 的元素
Stream filteredStream = combinedStream.filter(n -> n != 0);
// 将过滤后的流转换为数组
int[] newArr = filteredStream.toArray(); 4. 使用循环
int[] arr = {1, 2, 0, 4, 5, 0, 7};
int[] newArr = new int[arr.length];
int index = 0;
// 遍历数组
for (int n : arr) {
// 如果 n 不为 0,则将其添加到 newZeros
if (n != 0) {
newArr[index++] = n;
}
}









