用Java创建流的10种方法

2021年3月22日15:05:04 发表评论 648 次浏览

的流API, 是Java 8中引入的, 用于处理对象的集合。流是对象的序列, 它支持许多不同的方法, 可以通过管道进行管线排列以产生所需的结果。

Java流的功能是–

  • 流不是数据结构, 而是从集合, 数组或I / O通道获取输入。
  • Streams不会更改原始数据结构, 它们仅提供结果作为流水线方法。
  • 每个中间操作都是延迟执行的, 并因此返回流, 因此可以对各种中间操作进行管线处理。终端操作标记流的结尾并返回结果。

创建流的不同方法:

使用

采集

方法:

  1. 获取收藏
  2. 使用Collection.stream()方法从集合构造顺序流
  3. 打印流

下面是上述方法的实现:

程序:

// Java program to create Stream from Collections
  
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void getStream(List<T> list)
     {
  
         // Create stream object with the List
         Stream<T> stream = list.stream();
  
         // Iterate list first to last element
         Iterator<T> it = stream.iterator();
  
         // Iterate stream object
         while (it.hasNext()) {
             System.out.print(it.next() + " " );
         }
     }
  
     public static void main(String[] args)
     {
  
         // Create ArrayList of String
         List<String> list = new ArrayList<>();
  
         // Add element in list
         list.add( "Geeks" );
         list.add( "for" );
         list.add( "Geeks" );
  
         // Get the Stream from the List
         getStream(list);
     }
}

输出如下:

Geeks for Geeks

从指定值创建流

Stream.of(T…t)方法可用于创建具有指定t值的流, 其中t是元素。此方法返回包含t个元素的顺序Stream。

下面是上述方法的实现:

程序:

// Java program to create Stream from values
  
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
     // Function convert a List into Stream
     private static void getStream()
     {
  
         // Create a stream from specified values
         Stream<Integer> stream
             = Stream.of( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 );
  
         // Displaying the sequential ordered stream
         stream.forEach(p -> System.out.print(p + " " ));
     }
  
     public static void main(String[] args)
     {
  
         // Get the Stream from the values
         getStream();
     }
}

输出如下:

1 2 3 4 5 6 7 8 9

从数组创建流:

Stream.of()和Arrays.stream()

从指定数组创建顺序流的两种常用方法。当用非基本类型T调用时, 这两种方法都返回Stream。

整数数组

使用创建流

Arrays.stream()

程序:

// Java program to create Stream from Collections
  
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void getStream(T[] arr)
     {
  
         // Create stream from an array
         // using Arrays.stream()
         Stream<T> streamOfArray
             = Arrays.stream(arr);
  
         // Iterate list first to last element
         Iterator<T> it
             = streamOfArray.iterator();
  
         // Iterate stream object
         while (it.hasNext()) {
             System.out.print(it.next() + " " );
         }
     }
  
     public static void main(String[] args)
     {
  
         // Get the array
         String[] arr
             = new String[] { "a" , "b" , "c" };
  
         // Get the Stream from the Array
         getStream(arr);
     }
}

输出如下:

a b c

使用创建流

Stream.of()

当元素从流中消耗掉并返回新流时, 将对元素执行的无干扰操作。

程序:

// Java program to create Stream from Collections
  
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void getStream(T[] arr)
     {
  
         // Create stream from an array
         // using Stream.of()
         Stream<T> streamOfArray = Stream.of(arr);
  
         // Iterate list first to last element
         Iterator<T> it = streamOfArray.iterator();
  
         // Iterate stream object
         while (it.hasNext()) {
             System.out.print(it.next() + " " );
         }
     }
  
     public static void main(String[] args)
     {
  
         // Get the array
         String[] arr
             = new String[] { "a" , "b" , "c" };
  
         // Get the Stream from the Array
         getStream(arr);
     }
}

输出如下:

a b c

使用创建空流

Stream.empty()

创建时使用empty()方法, 以避免没有元素的流返回null。

程序:

// Java program to create empty Stream
  
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
     // Function convert a List into Stream
     private static void getStream()
     {
  
         // Create stream from an array using Stream.empty()
         Stream<String> streamOfArray
             = Stream.empty();
  
         // Iterate list first to last element
         Iterator<String> it
             = streamOfArray.iterator();
  
         // Iterate stream object
         while (it.hasNext()) {
             System.out.print(it.next() + " " );
         }
     }
  
     public static void main(String[] args)
     {
  
         // Get the empty Stream
         getStream();
     }
}

输出如下:

使用创建流

Stream.builder()

当在语句的右侧另外指定所需的类型时, 将使用builder()方法, 否则build()方法将创建Stream的实例。

程序:

// Java program to create Stream from Collections
  
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void getStream()
     {
  
         // Create stream using Stream builder()
         Stream.Builder<String> builder
             = Stream.builder();
  
         // Adding elements in the stream of Strings
         Stream<String> stream = builder.add( "a" )
                                     .add( "b" )
                                     .add( "c" )
                                     .build();
  
         // Iterate list first to last element
         Iterator<String> it = stream.iterator();
  
         // Iterate stream object
         while (it.hasNext()) {
             System.out.print(it.next() + " " );
         }
     }
  
     public static void main(String[] args)
     {
  
         // Get the Stream using Builder
         getStream();
     }
}

输出如下:

a b c

使用Stream.iterate()创建无限流

iterate()方法返回通过将函数f迭代应用到初始元素种子而生成的无限顺序有序Stream。在下面的示例中, 结果流的First元素是迭代方法的第一个参数。为了创建每个后续元素, 该功能将应用于上一个元素。在下面的示例中, 第二个元素为4。

程序:

// Java program to create infinite Stream
// using Stream.iterate() method
  
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void
     getStream( int seedValue, int limitTerms)
     {
  
         // Create infinite stream
         // using Stream.iterate() method
         Stream.iterate(seedValue, (Integer n) -> n * n)
             .limit(limitTerms)
             .forEach(System.out::println);
     }
  
     public static void main(String[] args)
     {
  
         // Get the seed value
         int seedValue = 2 ;
  
         // Get the limit for number of terms
         int limitTerms = 5 ;
  
         // Get the Stream from the function
         getStream(seedValue, limitTerms);
     }
}

输出如下:

2
4
16
256
65536

使用创建无限流

Stream.generate()

方法

generate()方法接受供应商生成元素, 并且结果流是无限的。因此, 要限制它, 请指定所需的大小, 否则generate()方法将起作用直到达到内存限制。

程序:

// Java program to create infinite Stream
// using Stream.generate() method
  
import java.util.*;
import java.util.stream.*;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void getStream( int limitTerms)
     {
  
         // Create infinite stream
         // using Stream.generate() method
         Stream.generate(Math::random)
             .limit(limitTerms)
             .forEach(System.out::println);
     }
  
     public static void main(String[] args)
     {
  
         // Get the limit for number of terms
         int limitTerms = 5 ;
  
         // Get the Stream from the function
         getStream(limitTerms);
     }
}

输出如下:

0.2293502475696314
0.5650334795948209
0.3418138293253522
0.36831074763500116
0.4864408670097241

通过创建流

模式

使用

谓词

在Java 8中, Pattern的Predicate asPredicate()方法创建一个用于模式匹配的谓词布尔值函数。

程序:

// Java program to create Stream from Collections
  
import java.util.*;
import java.util.stream.*;
import java.util.regex.Pattern;
  
class GFG {
  
     // Function convert a List into Stream
     private static void
     getStream(List<String> list, Pattern p)
     {
  
         list.stream()
             .filter(p.asPredicate())
             .forEach(System.out::println);
     }
  
     public static void main(String[] args)
     {
  
         // Create ArrayList of String
         // that is backed by the specified array
         List<String> list
             = Arrays
                   .asList( "Geeks" , "For" , "Geek" , "lsbin" , "A Computer Portal" );
  
         // Get the pattern
         Pattern p = Pattern.compile( "^G" );
  
         // Get the Stream from the List matching Pattern
         getStream(list, p);
     }
}

输出如下:

Geeks
Geek
lsbin

从创建流

迭代器

Java中的迭代器在Collection Framework中用于一一检索元素。分隔符是创建顺序流的关键。因此, 在该方法中, 也使用了Spliterator。但是在这种方法中, 将Spliterator的源设置为从Iterator创建的Iterable。因此, 首先从Iterator创建Iterable。然后, 将Spliterator作为Iterable.spliterator()直接传递到stream()方法。

程序:

// Java program to create Stream from Collections
  
import java.util.*;
import java.util.stream.*;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void getStream(Iterator<T> itr)
     {
  
         // Convert the iterator into a Spliterator
         Spliterator<T> spitr
             = Spliterators
                   .spliteratorUnknownSize(itr, Spliterator.NONNULL);
  
         // Convert spliterator into a sequential stream
         Stream<T> stream
             = StreamSupport.stream(spitr, false );
  
         // Iterate list first to last element
         Iterator<T> it = stream.iterator();
  
         // Iterate stream object
         while (it.hasNext()) {
             System.out.print(it.next() + " " );
         }
     }
  
     public static void main(String[] args)
     {
  
         // Get the Iterator
         Iterator<String> iterator = Arrays
                                         .asList( "a" , "b" , "c" )
                                         .iterator();
  
         // Get the Stream from the Iterator
         getStream(iterator);
     }
}

输出如下:

a b c

从创建流

可迭代的

可迭代接口的设计谨记在心, 它自己不提供任何stream()方法。只需将其传递到StreamSupport.stream()方法, 即可从给定的Iterable对象获取Stream。将Iterable转换为Stream更容易。 Iterable具有默认方法spliterator(), 该方法可用于获取Spliterator实例, 然后可以将其转换为Stream。

注意:Iterable不是Collection的实例, 此方法在内部调用StreamSupport.stream()以从Spliterator获取顺序的Stream, 否则它仅调用Collection.stream()方法。

程序:

// Java program to create Stream from Collections
  
import java.util.*;
import java.util.stream.*;
  
class GFG {
  
     // Function convert a List into Stream
     private static <T> void getStream(Iterable<T> iterable)
     {
  
         // Convert the iterator into a Stream
         Stream<T> stream
             = StreamSupport
                   .stream(iterable.spliterator(), false );
  
         // Iterate list first to last element
         Iterator<T> it = stream.iterator();
  
         // Iterate stream object
         while (it.hasNext()) {
             System.out.print(it.next() + " " );
         }
     }
  
     public static void main(String[] args)
     {
  
         // Get the Iterable
         Iterable<String> iterable
             = Arrays.asList( "a" , "b" , "c" );
  
         // Get the Stream from the Iterable
         getStream(iterable);
     }
}

输出如下:

a b c

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: