繁体   English   中英

从int转换为Integer并排序

[英]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方法来转换IntStreamStream ,然后你可以使用快捷方式Collectors.toList直接。

如果你不想从IntStream隐蔽通过调用到流boxed明确就可以直接使用

Arrays.stream(prize).sorted().collect(ArrayList::new,ArrayList::add,ArrayList::addAll);

它也会产生相同的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM