在我的程序中,我尝试使用流打印排序的 int 数组。但是我在使用普通流时得到错误的输出。使用 int 流时会打印正确的详细信息。
有关详细信息,请参阅下面的核心代码段。
package com.test.sort.bubblesort;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class BubbleSortWithRecursion {
public static void bubbleSort(int[] arr, int n) {
if (n < 2) {
return;
}
int prevValue;
int nextValue;
for (int index = 0; index < n-1; index++) {
prevValue = arr[index];
nextValue = arr[index+1];
if (prevValue > nextValue) {
arr[index] = nextValue;
arr[index+1] = prevValue;
}
}
bubbleSort(arr, n-1);
}
public static void main(String[] args) {
int arr[] = new int[] {10,1,56,8,78,0,12};
bubbleSort(arr, arr.length);
**//False Output** : [I@776ec8df
String output = Arrays.asList(arr)
.stream()
.map(x -> String.valueOf(x))
.collect(Collectors.joining(","));
System.out.println(output);
//Correct Output : 0,1,8,10,12,56,78
String output2 = IntStream
.of(arr)
.boxed()
.map(x -> Integer.toString(x))
.collect(Collectors.joining(","));
System.out.println(output2);
}
}
我在控制台上得到以下输出:
[I@776ec8df
0,1,8,10,12,56,78
第一行输出是使用不正确的普通 java 流生成的。
为什么我使用普通的 JAVA 流得到虚假内容?我在这里遗漏了什么吗?
最佳答案
您可以这样解决您的问题:
String output = Arrays.stream(arr)
.boxed()
.map(String::valueOf)
.collect(Collectors.joining(",")); // 0,1,8,10,12,56,78
解释发生了什么:
当你使用 Arrays.asList()
时:
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
它采用 T
类型的可变参数,在您的情况下,您将它用于 int[]
对象,因此 Arrays.asList()
将返回 int[]
的 List
而不是整数流,因此您必须使用如下所示的 Arrays.stream
:
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
获取正确的数据。
关于java - 使用普通 JAVA Stream 收集 int 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55321714/