题解 | #明明的随机数#
明明的随机数
https://www.nowcoder.com/practice/3245215fffb84b7b81285493eae92ff0
1. 使用Stream流
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Set<Integer> set = new HashSet<>();
while(n -- > 0){
set.add(sc.nextInt());
}
set.stream().sorted().forEach(x -> System.out.println(x));
}
}
在Java 8及更高版本中,Set 接口中引入了 stream() 方法,允许对其元素进行流式处理,包括排序。所以你的代码确实可以实现排序。
在你的代码中,set.stream().sorted().forEach(x -> System.out.println(x)) 这一行使用了流式处理来对 Set 中的元素进行排序,并逐个输出。
对于小规模的数据集,这样的实现方式是可以接受的。然而,在处理大规模数据时,可能会出现性能问题,因为它需要将所有元素加载到内存中并进行排序。而且,由于 HashSet 是无序的,排序后的顺序可能会受到哈希函数的影响。
对于大规模数据或者需要稳定排序的情况,更好的选择是使用 TreeSet 或者将 Set 转换为 List,然后使用 Collections.sort() 进行排序。这种方法更加高效和可控。
2. 使用迭代器
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//获取个数
int num = sc.nextInt();
//创建TreeSet进行去重排序
TreeSet set = new TreeSet();
//输入
for(int i =0 ; i < num ;i++){
set.add(sc.nextInt());
}
//输出
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}