[英]Convert from int to Integer and sort
我试图将int转换为List Integer以便应用stream方法对它们进行排序,但是它指出没有合适的方法。 有可能这样做吗?
public class Testsorting
{
public static int [] prize = {5,2,3,7,1,5,9,0,2};
public static void main(String [] args)
{
List<Integer> list = Arrays.stream(prize).
boxed().collect(Collectors.toList());
System.out.println(list);
List <Integer> sortedList = Arrays.stream(list) //error occured on this line
.sorted()
.collect(Collectors.toList());
}
}
将Arrays.stream(list)
更改为list.stream()
public class Main {
public static int [] prize = {5,2,3,7,1,5,9,0,2};
public static void main(String [] args)
{
List<Integer> list = Arrays.stream(prize).
boxed().collect(Collectors.toList());
System.out.println(list);
List <Integer> sortedList = list.stream() //error gone on this line
.sorted()
.collect(Collectors.toList());
System.out.println(sortedList);
}
}
只需执行以下操作即可实现这一目标。
Arrays.stream(prize).sorted().boxed().collect(Collectors.toList());
要么
Arrays.stream(prize).boxed().sorted().collect(Collectors.toList());
.stream
转换为IntStream
支持.sorted
方法开箱即用,但你不能收集IntStream
直接到像列表Collectors.toList()
因为这是在支持Stream
类,因此我们可以使用.boxed
方法来转换IntStream
到Stream
,然后你可以使用快捷方式Collectors.toList
直接。
如果你不想从IntStream隐蔽通过调用到流boxed
明确就可以直接使用
Arrays.stream(prize).sorted().collect(ArrayList::new,ArrayList::add,ArrayList::addAll);
它也会产生相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.