What is the difference between .stream() and Stream.of?

后端 未结 4 2061
别跟我提以往
别跟我提以往 2020-12-16 14:22

Which is the best way to create a stream out of a collection:

    final Collection entities = someService.getArrayList();
    <
4条回答
  •  误落风尘
    2020-12-16 14:44

    We can take a look at the source code:

    /**
     * Returns a sequential {@code Stream} containing a single element.
     *
     * @param t the single element
     * @param  the type of stream elements
     * @return a singleton sequential stream
     */
    public static Stream of(T t) {
        return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
    }
    
    /**
     * Returns a sequential ordered stream whose elements are the specified values.
     *
     * @param  the type of stream elements
     * @param values the elements of the new stream
     * @return the new stream
     */
    @SafeVarargs
    @SuppressWarnings("varargs") // Creating a stream from an array is safe
    public static Stream of(T... values) {
        return Arrays.stream(values);
    }
    

    As for Stream.of(), when the input variable is an array, it will call the second function, and return a stream containing the elements of the array. When the input variable is a list, it will call the first function, and your input collection will be treated as a single element, not a collection.

    So the right usage is :

    List list = Arrays.asList(3,4,5,7,8,9);
    List listRight = list.stream().map(i -> i*i).collect(Collectors.toList());
    
    Integer[] integer = list.toArray(new Integer[0]);
    
    List listRightToo = Stream.of(integer).map(i ->i*i).collect(Collectors.toList());
    

提交回复
热议问题