簡體   English   中英

.stream()和Stream.of有什么區別?

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

哪個是從集合中創建流的最佳方法:

    final Collection<String> entities = someService.getArrayList();
  1. entities.stream();

  2. Stream.of(entities);

第二個不符合你的想法! 沒有為您提供包含集合元素的流; 相反,它將為您提供一個包含單個元素的流,這是集合本身(而不是其元素)。

如果需要包含集合元素的流,則必須使用entities.stream()

1)

Stream<String> stream1 = entities.stream()

2)

Stream<Collection<String>> stream2 = Stream.of(entities)

所以使用1或2

Stream<String> stream3 = Stream.of("String1", "String2")

我自己一直對此感到困惑,所以我不妨把它留在這里以備將來參考:

import java.util.stream.IntStream;
import java.util.stream.Stream;

import static java.util.Arrays.*;
import static java.util.stream.Stream.*;

class Foo {
    void foo() {
        Stream<Foo> foo; 

        foo =     of(new Foo(), new Foo());
     // foo = stream(new Foo(), new Foo()); not possible

        foo =     of(new Foo[]{new Foo(), new Foo()});
        foo = stream(new Foo[]{new Foo(), new Foo()});

        Stream<Integer> integerStream; 

        integerStream =     of(1, 2);
     // integerStream = stream(1, 2); not possible

        integerStream =     of(new Integer[]{1, 2});
        integerStream = stream(new Integer[]{1, 2});

        Stream<int[]> intArrayStream =     of(new int[]{1, 2}); // count = 1!
        IntStream intStream          = stream(new int[]{1, 2}); // count = 2!
    }
}

我們可以看看源代碼:

/**
 * Returns a sequential {@code Stream} containing a single element.
 *
 * @param t the single element
 * @param <T> the type of stream elements
 * @return a singleton sequential stream
 */
public static<T> Stream<T> of(T t) {
    return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}

/**
 * Returns a sequential ordered stream whose elements are the specified values.
 *
 * @param <T> 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<T> Stream<T> of(T... values) {
    return Arrays.stream(values);
}

至於Stream.of() ,當輸入變量是一個數組時 ,它將調用第二個函數,並返回一個包含數組元素的流。 當輸入變量是一個列表時,它將調用第一個函數,並且您的輸入集合將被視為單個元素,而不是集合。

所以正確的用法是:

List<Integer> list = Arrays.asList(3,4,5,7,8,9);
List<Integer> listRight = list.stream().map(i -> i*i).collect(Collectors.toList());

Integer[] integer = list.toArray(new Integer[0]);

List<Integer> listRightToo = Stream.of(integer).map(i ->i*i).collect(Collectors.toList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM