Gun*_*hah 6 java arrays java-8 java-stream
在我的程序中,我试图使用流打印排序的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我在控制台上得到以下输出:
[I@776ec8df
0,1,8,10,12,56,78
Run Code Online (Sandbox Code Playgroud)
第一行输出是使用不正确的普通java流生成的。
为什么使用普通的JAVA流会收到虚假内容?我在这里想念什么吗?
您可以这样解决您的问题:
String output = Arrays.stream(arr)
.boxed()
.map(String::valueOf)
.collect(Collectors.joining(",")); // 0,1,8,10,12,56,78
Run Code Online (Sandbox Code Playgroud)
解释发生了什么:
当您使用Arrays.asList()
哪种外观时:
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
Run Code Online (Sandbox Code Playgroud)
花型的可变参数T
,你的情况,你使用它的int[]
对象,所以Arrays.asList()
会返回List
的int[]
,而不是整数流,所以不是你要使用Arrays.stream
它看起来像这样:
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
Run Code Online (Sandbox Code Playgroud)
获得正确的数据。
Arrays.asList(arr)
返回List<int[]>
其唯一元素为的arr
。因此,对该流进行流处理,List
然后将该单个元素映射到String.valueOf(x)
并进行收集Collectors.joining(",")
将导致String
其值是单个数组的toString()
,即您看到的输出。
String output = Arrays.asList(arr) // List<int[]>
.stream() // Stream<int[]>
.map(x -> String.valueOf(x)) // Stream<String> having a single element - "[I@776ec8df"
.collect(Collectors.joining(",")); // "[I@776ec8df"
Run Code Online (Sandbox Code Playgroud)
IntStream
从int
数组创建时,将获得单个元素(int
值)的流,因此可以将它们装箱,然后转换为String
s并将它们连接起来以获得所需的输出。
如果您进行以下更改,则可以使第一个代码段生效:
int arr[] = new int[] {10,1,56,8,78,0,12};
Run Code Online (Sandbox Code Playgroud)
至:
Integer arr[] = new Integer[] {10,1,56,8,78,0,12};
Run Code Online (Sandbox Code Playgroud)
因为这样Arrays.asList(arr)
会产生一个List<Integer>
包含输入数组所有元素的数组。
归档时间: |
|
查看次数: |
434 次 |
最近记录: |