简体   繁体   中英

Convert from int to Integer and sort

I am trying to convert from int to List Integer in order to apply the stream method to sort them, however it states that there's no suitable method. Is it possible to do it this way?

    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());
    }
}

Change Arrays.stream(list) to 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);
    }
}

Just do below to achieve this in one line.

Arrays.stream(prize).sorted().boxed().collect(Collectors.toList());

or

Arrays.stream(prize).boxed().sorted().collect(Collectors.toList());

.stream converts to IntStream that supports .sorted method ootb but you can not collect IntStream directly into list like Collectors.toList() because this is supported in Stream class therefore we can use .boxed method to convert IntStream to Stream and you can then use shortcut Collectors.toList directly.

If you don't want to covert from IntStream to Stream by calling boxed explicitly you can use directly

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

It will also give the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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