【
Core JavaLearning notes Java SE8 Stream library stream from iteration to stream
If you want to calculate how many long words are in a text (letter >12).
Create a Stream
- If there is a
Collection
class, call its stream()
or other stream method.
- If there is an array, use the
Stream.of(Array array)
method.
- Creates an empty stream, calling the
Stream.empty()
method.
-
Creates an infinite stream, calling the stream.generate (Supplier supplier<t> s)
method.
stream<string> Echos = Stream. (()-> "Echo" ); //above the lambda expression can be written as the following complete expression Stream<string> Echos = Stream. generate (new supplier<string> () { @Override p Ublic String get () {return "echo" ; } });
stream<double> randoms = Stream. (math::random); //produces a random number, a double colon is a method in a lambda expression that references
Creates an infinite long stream of iterations, using theStream.iterate(T seed,UnaryOperator f)
Stream<BigInteger> integers = Stream.iterate(BigInteger.ZERO,n->n.addd(BigInteger.ONE))//流的第一个元素为seed,后续元素为f(seed),f(f(seed))...
String to create a stream that invokes Pattern
a method in a class spliteAsStream(CharSequence input)
Pattern pattern = Pattern.compile(" ");Stream<String> s = pattern.splitAsStream("A B C");
filter
,
map
And
flatmap
Method
The most commonly used three kinds of intermediate operations
Stream<T> filter
Methods: Select elements that meet certain criteria in the source stream to form a new flow.
List<String> wordList = ...; //省略初始化Stream<String> longWords = wordList.Stream().filter(w -> w.length12);
<R> Stream<R> map
Method: The new stream is formed after performing the same operation on all elements in the source.
List<String> words = ...; //省略初始化Stream<String> lowercaseWords = words.stream().map(String::toLowerCase);
<R> Stream<R> flatmap
Method: The map
effect is roughly the same as the method, but a flow that consists of multiple streams will be merged. That is, the stream
Extracting sub-streams and merging streams
Called Stream<T> limit(n)
to fetch the sub-stream of the first n elements.
Stream<Double> randoms = Stream.generate(Math::random).limit(100);
Called Stream<T> skip(n)
to get a sub-stream that skips the first n elements
Stream<String> words = Stream.of(contents.split("\\PL+")).skip(1);
Called Stream<T> concate(Stream a,Stream b)
to create a A/b stream after the merged stream after a.
Other Stream conversion operations
Stream<T> distinct()
Get the same order, but keep only one stream of the same item.
Stream<String> uniqueWords = Stream.of("a","a","b","c","a").distinct();
Use Stream<T> sorted()
to sort comparable, or use Stream<T> sorted(Comparator<? super T> comparator)
to sort ordinary object elements.
Stream<String> longestFirst = words .stream() .sorted(Comparator.comparing(String::length)) .reversed();
Use to Stream<T> peek(Consumer<? super T> action)
trigger an action whenever an element is actually accessed (action), which facilitates debug.
Object[] powers = Stream.iterate(1.02) .peek(e - > System.out.println("Peeking"+e)) .limit(20).toArrays();
Simple Restore (reduction) operation
- A restore operation is an operation that transforms a stream object into a non-streaming object.
- The restore operation is a terminate operation (terminal Operations), and the stream is not available after the operation.
count()
Calculates the number of elements in the stream. (previous example)
max(Comparator<? super T> comparator)
And min(Comparator<? super T> comparator)
get the maximum/minimum element. They return a Optional<? super T>
class.
Optional<String> largest = words.max(String::compareToIgnoreCase);System.out.println("largest:" + largest.orElse(""));
findFirst()
and findAny()
get filter filter to the first/all elements. They return a Optional<? super T>
class.
Optional<String> startsWithQ = words.filter(s -> s.startWith("Q")).findFirst();
anyMatch(Predicate<? super T> p)
, allMatch(Predicate<? super T> p)
and noneMatch(Predicate<? super T> p)
returns a matching result (Boolean).
boolean aWordStartsWithQ = words.parallel().anyMatch(s -> s.startWith("Q"));
Optional
Class
Optional
Class is a common return value for a stream restore operation. Optional<T>
holds (Wrap) object of type T or null. This design idea is for the sake of safety, avoid null references.
Simply handle
Optional
Object that is held in the object.
T orElse(T other)
If the Optional
object is not empty, it returns the owning object, otherwise other
.
String result = optionalString.orElse("");//return wrapped string, or "" if null
T orElseGet(Supplier<? extends T> other)
Returns the Optional
owning object if the object is not empty, otherwise returnsother.get()
T orElseThrow(Supplier<? extends X> exceptionSupplier)
Optional
returns the owning object if the object is not empty, or throws an exceptionSupplier.get()
exception.
ifPresent
Accepts a function that is handled if option holds the object, otherwise nothing happens.
optionValue.ifPresent(v -> Process v);
。 The method has no return value.
map
Method and ifPresent
similar, but there is a Optional<T>
return value, the original Optional<T>
object does not change.
Use correctly
Optional
Class
Always be alert that Optional
objects may not hold objects. This feature can cause NoSuchElementException
errors to be thrown.
Optional<T> optionValue = ...;optionValue.get().someMethod();//not safe, cause get() may produce null
Optional<T> optionValue = ...;if(optionValue.isPresent())optionValue.get().someMethod();//safe, cause isPresent() reports whether an Optional object has a value
CreateOptional
Object of the classOptional
the primary method for creating an object is Optional
to invoke the static factory method of the class.
static <T> Optional<T> of(T value)产生一个Optional对象,如果value是null,则抛出异常static <T> Optional<T> ofNullable(T value)产生一个Optional对象。static<T> Optional
PassflatMap
Method invocationOptional<T>
Object holds the method of the T object.
//f() yields an Optional<T>//T has a method g() yields an Optional<U> Optional<U> result = s.f().flatMap(T::g)
Collection stream into the collection
Display Stream
stream.forEach(System.out::println);
Get array
String[] result = stream.toArray(String::new);//toArray get Object[], pass it to constructor to get the right type.
Use collect
the methods and the Collectors
many factory methods in the class to get a collection of objects in different containers.
list<string> result = stream.Collect(Collectors.toList()); set<string> result = stream.Collect(Collectors.Toset()); treeset<string> result = stream.Collect(Collectors.tocollection(TreeSet::New));//control which type of implementation of CollectionString result = stream.Collect(Collectors.joining()); String result = stream.Collect(Collectors.joining(", "));//joing to one Stringiterator<t> Iterator = stream.iterator(); intsummarystatistics summary = stream.Collect(Collectors.Summarizingint(String::length));DoubleAveragewordlength = Summary.Getaverage();DoubleMaxwordlength = Summary.Getmax();//summarizing (int| long|double) (int| Long| Double) Summarystatistisc
Collection stream into the dictionary
For example, there is a person class
Person{ privateint id; private String name; publicgetId(){ return id; } publicgetName(){ return name; } publicPerson(int id,String name){ this.id = id; this.name = name; }}
Map<Integer, String> keyToValue = stream.collect( Collectors.toMap(Person::getID,Person::getName)); //(Function keyMapper, Function valueMapper)
- The entire object as a key/value
Map<Integer, Person> idToPerson = stream.collect( Collectors.toMap(Person::getID,Function.identity()));
Java 8 Stream Library Learning notes (i)