下载  >  开发技术  >  Java  > core java 11 第二卷

core java 11 第二卷 评分:

core java 11最新版第二卷,非印刷版,排版质量差,介意勿下。
Chapter 1 Streams In this chapter 1.1 From Iterating to Stream operations 1.2 Stream Creation 1.3 The filter, map, and flatMap Methods 1.4 Extracting Substreams and Combining Streams 1.5 Other Stream Transformations 1.6 Simple reductions ·17 The Optional Type 1.8 Collecting Results 1.9 Collecting into Maps 1.10 Grouping and Partitioning 1.11 Downstream Collectors 1.12 Reduction Operations 1.13 Primitive Type Streams 1.14 Parallel Streams Streams provide a view of data that lets you specify computations at a higher conceptual level than with collections With a stream, you specify what you want to have done, not how to do it. You leave the scheduling of operations to the implementation. For example, suppose you want to compute the average of a certain property You specify the source of data and the property, and the stream library can then optimize the computation, for example by using multiple threads for computing sums and counts and combining the results In this chapter, you will learn how to use the Java stream library, which was introduced in Java 8, to process collections in a" what, not how style 1.1 FROM ITERATING TO STREAM OPERATIONS When you process a collection, you usually iterate over its elements and do some work with each of them. For example, suppose we want to count all long words in a book First, let's put them into a list: var contents new String(Files. readAllBytes( Paths. get("alice. txt")), Standardcharsets UTF 8);//Read List<string> words= List of(contents. split(\\PI+))i / Split into words; nonletters are delimiters Now we are ready to iterate: int count =0 for (string w: words) t if(wlength()>12)count++ With streams, the same operation looks like this long count = words. stream() filter(w - Wlength()> 12 county Now you don' t have to scan the loop for evidence of filtering and counting. The method names tell you right away what the code intends to do. Moreover, where the loop prescribes the order of operations in complete detail, a stream is able to schedule the operations any way it wants, as long as the result is correct Simply changing stream into parallelstream allows the stream library to do the filtering and counting in parallel long count words. parallelStream() filter(w-> wlength()> 12 count( Streams follow the"what, not how"principle In our stream example, we describe what needs to be done: get the long words and count them. We don' t specify in which order, or in which thread, this should happen. In contrast, the loop at the beginning of this section specifies exactly how the computation should work, and thereby forgoes any chances of optimization a stream seems superficially similar to a collection, allowing you to transform and retrieve data. But there are significant differences 1. A stream does not store its elements. They may be stored in an underlying collection or generated on demand 2. Stream operations dont mutate their source. For example, the filter method does not remove elements from a stream, but it yields a new stream in which they are not present 3. Stream operations are lazy when possible. This means they are not executed until their result is needed. For example, if you only ask for the first five long words instead of all, the filter method will stop filtering after the fifth match. As a consequence you can even have Infinite streams Let us have another look at the example. The stream and parallelstream methods yield a stream for the words list. The filter method returns another stream that contains only the words of length greater than twelve. The count method reduces that stream to a result This workflow is typical when you work with streams. You set up a pipeline of operations in three stages 1. Create a stream 2. Specify intermediate operations for transforming the initial stream into others possibly in multiple steps 3. Apply a terminal operation to produce a result. This operation forces the execution of the lazy operations that precede it. Afterwards, the stream can no longer be used In the example in Listing 1.1, the stream is created with the stream or parallelstream method The filter method transforms it, and count is the terminal operation In the next section, you will see how to create a stream. The subsequent three sections deal with stream transformations. They are followed by five sections on terminal operations. Listing 1.1 streams/CcuntLongNords. java package streams 大 version1.012018-05-01 大 author Cay horstmann mport java. io g import jav harset 10 import java nio file. t 11 import java. util 13 public class CountLongWords 14{ public static void main(String[ args) throws IOExcep var contents new String(Files. readAllBytes( 18 Paths. get(./gutenberg/alice30txt")), stan 19 List<string> words List of(contents. split("\PL+ 20 21 ong count =0; 22 for (String w: words) 23 24 (w,⊥ ength 12) count++ System. out. println(count)i 27 28 count words stream(). filter(w - wlength() System. out. printIn(count)i 31 count words parallelstream().filter(w - Wlen System. out. println(count)i javautil. stream Stream<T>8 .Stream<T> filter (Predicate<? super T> p yields a stream containing all elements of this stream fulfilling p long count () yields the number of elements of this stream. This is a terminal operation javautil. Collection <E>1.2 default Stream<e> stream( o default stream<E> parallelstream() yields a sequential or parallel stream of the elements in this collection 1。2 STREAM CREATION You have already seen that you can turn any collection into a stream with the stream method of the Collection interface. If you have an array, use the static stream of method instead Stream<string> words= Stream of(contents. split(\PL+"))i / split returns a String[] array The of method has a varargs parameter, so you can construct a stream from any number of arguments Stream<string> song Stream of("gently ,down",the,stre Use Arrays. stream(array, from, to) to make a stream from a part of an array To make a stream with no elements, use the static stream. empty method: Stream<string> silence stream empty()i / Generic type <String> is inferred; same as Stream. <stri The Stream interface has two static methods for making infinite streams. The generate method takes a function with no arguments(or, technically, an object of the Supplier<r> interface). Whenever a stream value is needed, that function is called to produce a value. You can get a stream of constant values as Stream<string> echos Stream generate(()-> Echo or a stream of random numbers as Stream<Double> randoms Stream generate(Math:: random)i To produce sequences such as 0 1 3 use the iterate method instead. It takes a" value and a function(technically, a Unaryoperator<t>) and repeatedly applies the function to the previous result. For example, Stream<BigInteger> integers Stream iterate(BigInteger. ZERO, n - n add (bigInteger. ON The first element in the sequence is the seed BigInteger. ZERO. The second element is f(seed), or 1 (as a big integer). The next element is f(f(seed)), or 2, and so on To produce a finite stream instead, add a predicate that specifies when the iteration should finish var limit= new BigInteger(10000000)i tream<BigInteger> integers Stream iterate(BigInteger. ZERO, n.comparefo(limit)<0 n->n add(BigInteger. ONE))i As soon as the predicate rejects an iteratively generated value, the stream ends Finally, the stream. ofNullable method makes a really short stream from an object The stream has length o if the object is null or length 1 otherwise, containing just the object. This is mostly useful in conjunction with flatMap-see Section 1. 7.7, Turning an Optional into a Stream, on p. 22 for an example.

...展开详情
2018-12-29 上传 大小:39.04MB
举报 收藏
分享