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

后端 未结 4 2032
别跟我提以往
别跟我提以往 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:34

    I myself keep getting confused about this so I might as well leave this here for future reference:

    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 =     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 integerStream; 
    
            integerStream =     of(1, 2);
         // integerStream = stream(1, 2); not possible
    
            integerStream =     of(new Integer[]{1, 2});
            integerStream = stream(new Integer[]{1, 2});
    
            Stream intArrayStream =     of(new int[]{1, 2}); // count = 1!
            IntStream intStream          = stream(new int[]{1, 2}); // count = 2!
        }
    }
    

提交回复
热议问题