Java 8 Stream Library Learning notes (i)

Source: Internet
Author: User
Tags java 8 stream

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).

  • Iterative type:

    getlist();//虚构方法,获得一个List<String>long0;for(String w:words){if(w.length()>12) count++;}
  • Flow type:

    getlist();//虚构方法,获得一个List<String>long count = words.stream().filter(w->w.length12).count();
  • The benefits of a streaming expression relative to an iteration:
    1. Easy to read.
    2. Easy to optimize, for example, the method can be used for steam() parallelStream() parallel computing.
    3. Follow the "What, isn't how" principle, higher levels of abstraction.
  • Characteristics of the stream:
    1. Streams do not store elements, and elements may be stored in an anonymous collection that is generated on demand.
    2. Stream operations will never change the source data. For example filter() , the method does not remove the data, but instead produces a new stream.
    3. The flow operation is lazy , which means that the operation is not performed until the result of the flow action is required.
  • Paradigm of flow operations:
    1. Create a stream. For example, the above examplestream()
    2. The application intermediate operations uses the original stream to generate the other required streams, which can be multi-step. For example, the above examplefilter()
    3. Application terminal operation to produce results. The stream will not be available after that. For examplecount()
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, mapAnd flatmapMethod

The most commonly used three kinds of intermediate operations

  • Stream<T> filterMethods: 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> mapMethod: 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> flatmapMethod: 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"));
OptionalClass

OptionalClass 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 OptionalObject 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)Optionalreturns the owning object if the object is not empty, or throws an exceptionSupplier.get() exception.
    • ifPresentAccepts a function that is handled if option holds the object, otherwise nothing happens.
      optionValue.ifPresent(v -> Process v);。 The method has no return value.
    • mapMethod and ifPresent similar, but there is a Optional<T> return value, the original Optional<T> object does not change.

Use correctly OptionalClass
  • 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
    CreateOptionalObject of the class

    Optionalthe 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
    PassflatMapMethod 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;    }}
    • General situation
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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.