Java8InAction-Stream
1、什么是流
提到流,首先想到的就是Linux中的管道,它可以将几个函数的输入和输出连接起来。
Stream也可以达到类似的效果,它在内部维护了数据迭代的过程,我们不用处理数据的迭代,
同时,它为我们提供了一些接口,使得我们可以对流中的数据进行处理。
经过Stream的抽象后,对数据的处理就像流水线一样,
我们从一个源得到数据流,然后,在流水线上的工位上(接口,中间操作)对数据进行处理,
然后在流水线尽头(终端操作)将数据按一定方式打包。
Stream的抽象使得我们可以采用声明式的方式来处理数据,只需要描述要做什么,而不用处理细节。
采用Stream书写的代码:
1、声名性;
2、可复合,中间操作可以连接;
3、可并行,中间操作是同时进行的。
2、流特点
流是从支持数据处理操作的源生成的元素序列,它描述的是对数据的处理。
流与集合的关系是很密切的,集合是流的源之一。
集合与流的差异在于在什么时候进行计算,集合是立即计算的,每一个集合元素都是确定的,
但是,流不一样,流中的元素是懒生成的,只有到需要的时候才进行计算,就像Python中的生成器一样。。
流是一次性的,就像流水线一样,有限的源总会走到流水线尽头的。
3、流操作
中间操作:
返回的结果仍然是一个流,仍可以进行操作。
终端操作:
返回的结果不是一个流,流处理的尽头。
总而言之,流的使用可以分为三个部分:
1、创建流,从数据源得到数据序列;
2、中间操作链,形成一条流的流水线;
3、终端操作,执行流水线,得到结果。
4、常用操作
摘自JavaSE8doc:
boolean |
allMatch(Predicate<? super T> predicate)
Returns whether all elements of this stream match the provided predicate.
|
boolean |
anyMatch(Predicate<? super T> predicate)
Returns whether any elements of this stream match the provided predicate.
|
static <T> Stream.Builder<T> |
builder()
Returns a builder for a
Stream. |
<R,A> R |
collect(Collector<? super T,A,R> collector)
Performs a mutable reduction operation on the elements of this stream using a
Collector. |
<R> R |
collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
Performs a mutable reduction operation on the elements of this stream.
|
static <T> Stream<T> |
concat(Stream<? extends T> a, Stream<? extends T> b)
Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
|
long |
count()
Returns the count of elements in this stream.
|
Stream<T> |
distinct()
Returns a stream consisting of the distinct elements (according to
Object.equals(Object)) of this stream. |
static <T> Stream<T> |
empty()
Returns an empty sequential
Stream. |
Stream<T> |
filter(Predicate<? super T> predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.
|
Optional<T> |
findAny()
Returns an
Optional describing some element of the stream, or an empty Optional if the stream is empty. |
Optional<T> |
findFirst()
Returns an
Optional describing the first element of this stream, or an empty Optional if the stream is empty. |
<R> Stream<R> |
flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
|
DoubleStream |
flatMapToDouble(Function<? super T,? extends DoubleStream> mapper)
Returns an
DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. |
IntStream |
flatMapToInt(Function<? super T,? extends IntStream> mapper)
Returns an
IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. |
LongStream |
flatMapToLong(Function<? super T,? extends LongStream> mapper)
Returns an
LongStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. |
void |
forEach(Consumer<? super T> action)
Performs an action for each element of this stream.
|
void |
forEachOrdered(Consumer<? super T> action)
Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.
|
static <T> Stream<T> |
generate(Supplier<T> s)
Returns an infinite sequential unordered stream where each element is generated by the provided
Supplier. |
static <T> Stream<T> |
iterate(T seed, UnaryOperator<T> f)
Returns an infinite sequential ordered
Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. |
Stream<T> |
limit(long maxSize)
Returns a stream consisting of the elements of this stream, truncated to be no longer than
maxSize in length. |
<R> Stream<R> |
map(Function<? super T,? extends R> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream.
|
DoubleStream |
mapToDouble(ToDoubleFunction<? super T> mapper)
Returns a
DoubleStream consisting of the results of applying the given function to the elements of this stream. |
IntStream |
mapToInt(ToIntFunction<? super T> mapper)
Returns an
IntStream consisting of the results of applying the given function to the elements of this stream. |
LongStream |
mapToLong(ToLongFunction<? super T> mapper)
Returns a
LongStream consisting of the results of applying the given function to the elements of this stream. |
Optional<T> |
max(Comparator<? super T> comparator)
Returns the maximum element of this stream according to the provided
Comparator. |
Optional<T> |
min(Comparator<? super T> comparator)
Returns the minimum element of this stream according to the provided
Comparator. |
boolean |
noneMatch(Predicate<? super T> predicate)
Returns whether no elements of this stream match the provided predicate.
|
static <T> Stream<T> |
of(T... values)
Returns a sequential ordered stream whose elements are the specified values.
|
static <T> Stream<T> |
of(T t)
Returns a sequential
Stream containing a single element. |
Stream<T> |
peek(Consumer<? super T> action)
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
|
Optional<T> |
reduce(BinaryOperator<T> accumulator)
Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an
Optional describing the reduced value, if any. |
T |
reduce(T identity, BinaryOperator<T> accumulator)
Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value.
|
<U> U |
reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.
|
Stream<T> |
skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first
n elements of the stream. |
Stream<T> |
sorted()
Returns a stream consisting of the elements of this stream, sorted according to natural order.
|
Stream<T> |
sorted(Comparator<? super T> comparator)
Returns a stream consisting of the elements of this stream, sorted according to the provided
Comparator. |
Object[] |
toArray()
Returns an array containing the elements of this stream.
|
<A> A[] |
toArray(IntFunction<A[]> generator)
Returns an array containing the elements of this stream, using the provided
generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing. |
5、使用流-例子
package Stream; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Stream { static List<Transaction> transactions = Arrays.asList( new Transaction(new Trader("lala", "WuHan"), 2000d,1990), new Transaction(new Trader("haha", "WuHan"), 1900d,1980), new Transaction(new Trader("hehe", "Beijing"), 2300d,2000), new Transaction(new Trader("baba", "Chengdu"), 5000d,2010), new Transaction(new Trader("babe", "Chengdu"), 10000d,2010), new Transaction(new Trader("baby", "Chengdu"), 5000d,2010), new Transaction(new Trader("gaga", "Chengdu"), 4000d,2010), new Transaction(new Trader("xiexie", "Chengdu"), 9000d,2010), new Transaction(new Trader("nihao", "Chengdu"), 8000d,2010), new Transaction(new Trader("zaijian", "Chengdu"), 15000d,2010) ); public static void main(String[] args) { //最小交易额 transactions.stream().mapToDouble(i -> i.getValue()).sorted().limit(1).forEach(System.out::println); System.out.println(transactions.stream().mapToDouble(i -> i.getValue()).reduce(Math::min).orElse(-1)); //交易额总和 System.out.println(transactions.stream().mapToDouble(i -> i.getValue()).reduce(Double::sum).orElse(0)); //查找所有来自成都的交易员,按名字排序 transactions.stream().filter(i-> i.getTrader().getCity().equals("Chengdu")).map(i->i.getTrader().getName()).sorted(Comparator.comparing(String::toString)).forEach(System.out::println); //打印所有的城市 transactions.stream().map(i->i.getTrader().getCity()).distinct().forEach(System.out::println); //打印交易额前三的交易员姓名 transactions.stream().sorted((i,j)->{ if(i.getValue()>j.getValue()) return -1; else if(i.getValue().equals(j.getValue())) return 0; else return 1; }).limit(3).map(i->i.getTrader().getName()).forEach(System.out::println); transactions.stream().sorted(Comparator.comparing(Transaction::getValue).reversed()).limit(3).map(i->i.getTrader().getName()).forEach(System.out::println); //将交易按 交易员姓名 交易员城市 交易额 的格式打印 transactions.stream().map(i->i.getTrader().getName()+' '+i.getTrader().getCity()+' '+i.getValue()+' ').forEach(System.out::println); //将所有在2010年有交易的交易员按照交易值从大到小的顺序排序。 transactions.stream().filter(i->i.getYear()==2010).sorted(Comparator.comparing(Transaction::getValue).reversed()).forEach(i-> System.out.println(i.getTrader().getName())); } }
6、创建流
1、由值创建
Stream.of():
Stream<String> language=Stream.of("java","python","C","C++","C#","Go");
2、由数组创建
Arrays.stream(T arrray):
int[] numbers={1,2,3,4,5,6,7,8,9};
IntStream nums=Arrays.stream(numbers);
3、由文件创建
static Stream<Path> |
find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options)
Return a
Stream that is lazily populated with Path by searching for files in a file tree rooted at a given starting file. |
static Stream<String> |
lines(Path path)
Read all lines from a file as a
Stream. |
static Stream<String> |
lines(Path path, Charset cs)
Read all lines from a file as a
Stream. |
static Stream<Path> |
list(Path dir)
Return a lazily populated
Stream, the elements of which are the entries in the directory. |
static Stream<Path> |
walk(Path start, FileVisitOption... options)
Return a
Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. |
static Stream<Path> |
walk(Path start, int maxDepth, FileVisitOption... options)
Return a
Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. |
4、由函数生成,创建无限流
static <T> Stream<T> |
iterate(T seed, UnaryOperator<T> f)
Returns an infinite sequential ordered
Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. |
static <T> Stream<T> |
generate(Supplier<T> s)
Returns an infinite sequential unordered stream where each element is generated by the provided
Supplier. |
java.util.stream.Stream<int[]> fib=java.util.stream.Stream.iterate(new int[]{0,1}, t->new int[]{t[1],t[0]+t[1]}); fib.limit(20).forEach(t->System.out.printf("%d\n",t[0]));

浙公网安备 33010602011771号