创建Stream
从 Collection
- stream()
- parallelStream()
举例:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
list.add("Stream");
list.stream().forEach(System.out::println);
list.parallelStream().forEach(System.out::println);
}
/*
结果:
Hello
World
Stream
World
Stream
Hello
*/
数组
- Arrays.stream(T array)
- Stream.of()
举例:
public static void main(String[] args) {
String[] array = {"Hello","World","Stream"};
Arrays.stream(array).forEach(System.out::println);
Stream.of(array).forEach(System.out::println);
}
流的操作
流的操作类型
- Intermediate:一个流可以后面跟随零个或多个 intermediate 操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的(lazy),就是说,仅仅调用到这类方法,并没有真正开始流的遍历。
- Terminal:一个流只能有一个 terminal 操作,当这个操作执行后,流就被使用“光”了,无法再被操作。所以这必定是流的最后一个操作。Terminal 操作的执行,才会真正开始流的遍历,并且会生成一个结果,或者一个 side effect。
流的操作
- map
/**
* Returns a stream consisting of the results of applying the given
* function to the elements of this stream.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param <R> The element type of the new stream
* @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* function to apply to each element
* @return the new stream
*/
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
通过源码上的注释了解到,map主要使用名为mapper 的Function函数执行转换操作。
public static void main(String[] args) {
String[] array = {"Hello","World","Stream"};
Stream.of(array).map(String::toUpperCase).forEach(System.out::println);
}
- filter
/**
* Returns a stream consisting of the elements of this stream that match
* the given predicate.
*
* <p>This is an <a href="package-summary.html#StreamOps">intermediate
* operation</a>.
*
* @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
* <a href="package-summary.html#Statelessness">stateless</a>
* predicate to apply to each element to determine if it
* should be included
* @return the new stream
*/
Stream<T> filter(Predicate<? super T> predicate);
filter方法返回通过predicate测试的元素所组成的流。
public static void main(String[] args) {
String[] array = {"Hello", "World", "Stream", "is", "we"};
Predicate<String> predicate = (ele) -> ele.length() > 4;
Stream.of(array).filter(predicate).forEach(System.out::println);
}
网友评论