What is a Stream

Stream is not a collection element and is not a data structure, so it cannot hold data. Stream only needs to give what operation needs to be performed on the elements it contains (such as filtering the string whose length meets the specified length, etc.), and Stream will implicitly iterate internally and make the corresponding data transformation, which is equivalent to data processing on the pipeline. After processing, we can get the data we want.

Several commonly used functional interfaces

Before we start learning about streams, we need to understand several common functional interfaces:

  • Function Indicates a functional interface
/** * Function * Public static void main(String[] args) {Function Function = new Function<String, String>() { @Override public String apply(String str) { return str; }}; Function<String, String> function2 = (STR) -> {return STR; }; System.out.println(function2.apply("asd")); }Copy the code
  • Predicate interface

/** * Predicate * takes one input argument, and returns only Boolean values, */ public static void main(String[] args) {// Allows you to Predicate whether the String is empty. Predicate PC = new <String>() {@override public boolean test(String str) { return str.isEmpty(); }}; System.out.println(pc.test("qwew")); Predicate<String> pre =(STR)->{return str.isempty (); }; System.out.println(pre.test("")); }Copy the code
  • Customer Consumer interface

/** * ConsumerInterface */ public class ConsumerInterface {public static void main(String[] args) {Consumer<String> stringConsumer  = new Consumer<String>() { @Override public void accept(String str) { System.out.println(str); }}; <String> Consumer =(STR)->{system.out.println (STR); }; Consumer. Accept (" print STR "); }}Copy the code
  • Supplier Supplier interface

Public class SupplierInterface {public static void main(String[] args) {Supplier<String> Supplier = new Supplier<String>() {@override public String get() {return "supply interface "; }}; // simplified Supplier<String> sp =()->{return "supply interface "; }; System.out.println(sp.get()); }Copy the code

How to get Stream

  • The stream is obtained from the stream() method of the Collection interface
public interface Collection<E> extends Iterable<E> { default Stream<E> stream() { return StreamSupport.stream(spliterator(), false); }}Copy the code
ArrayList<Integer> list = new ArrayList<>();
        
Stream<Integer> stream = list.stream();
Copy the code
  • The Stream Stream is obtained through the static of() method of the Stream interface
public interface Stream<T> extends BaseStream<T, Stream<T>> { @SafeVarargs @SuppressWarnings("varargs") // Creating a stream from an array is safe public static<T> Stream<T> of(T... values) { return Arrays.stream(values); }}Copy the code
Stream<String> stream = Stream.of("a","b","c","d","e");
Copy the code

Stream API

  • Two classifications of methods in Stream
  1. Finalizer methods, such as count() and forEach(), do not execute if the finalizer method of Stream is not called last.
  2. Non-finalizing methods (function concatenation methods), such as the filter() method, return a new Stream.
  • The forEach() method, which iterates over the elements in the stream
void forEach(Consumer<? super T> action);
Copy the code

Example:

List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.stream().forEach((str)->{ System.out.println(str); }); / / short list. The stream (). The forEach (System. Out: : println);Copy the code
  • The count() method to calculate the length of the elements in the stream
long count();
Copy the code
  • The filter() method filters out elements that match the specified criteria
Stream<T> filter(Predicate<? super T> predicate);
Copy the code

Example:

{return STR. Equals ("a");} return STR. Equals ("a"); }).forEach(System.out::println);Copy the code
  • The limit(long n) method to filter the first N elements from the stream
Stream<T> limit(long maxSize);
Copy the code

Example:

List.stream ().limit(2).foreach (system.out ::println);Copy the code
  • If n is 0, the number of elements in the stream will not be changed. If the original stream has 4 elements a, B, C and d, when n is 1, the new stream containing 3 elements b, C and d will be returned.
Stream<T> skip(long n);
Copy the code

Example:

list.stream().skip(1).forEach(System.out::println);
Copy the code
  • The map() method to map elements in a flow to another flow
<R> Stream<R> map(Function<? super T, ? extends R> mapper);Copy the code

Example:

public class User { private String name; private int age; private int id; } User u1 = new User("a", 11, 1); User u2 = new User("b", 12, 2); User u3 = new User("c", 24, 12); User u4 = new User("d", 34, 4); List<User> users = Arrays.asList(u1, u2, u3, u4); users.stream().map((u)->{ return u.getName()+u.getAge(); }).forEach(System.out::println); List<String> List = new ArrayList<>(); list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.stream().map((str)->{ return Integer.parseInt(str); }).forEach(System.out::print);Copy the code
  • The flatMap() method flattens the convection
    <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
Copy the code

Example:

String[] string = {"a","b","c","d"}; list.stream().flatMap((str)-> Arrays.stream(string)).forEach(System.out::print); Output: abcd abcd abcd abcd abcdCopy the code
  • The sorted() method sorts the data in the stream
Stream<T> sorted();

Stream<T> sorted(Comparator<? super T> comparator);

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}
Copy the code

Example:

List<Integer> list = new ArrayList<>();
        list.add(13);
        list.add(12);
        list.add(8);
        list.add(4);
        
        list.stream().sorted((str1,str2)->(str1-str2)).forEach(System.out::println);
Copy the code
  • The distinct() method removes duplicate data
 Stream<T> distinct();
Copy the code

Example:

List<Integer> list = new ArrayList<>(); list.add(13); list.add(12); list.add(12); list.add(8); list.add(4); list.add(4); List. The stream (). Distinct (). The forEach (System. Out: : println); Output: 13, 12, 8, 4Copy the code
  • The allMatch(), anyMatch(), and nonMatch() methods determine whether the data matches the specified condition
//allMatch() : Boolean allMatch(Predicate<? super T> predicate); Boolean anyMatch(Predicate<?); // Predicate<? super T> predicate); NonMatch () : Boolean noneMatch(Predicate<? super T> predicate);Copy the code

Example:

List<Integer> list = new ArrayList<>(); list.add(13); list.add(12); list.add(8); list.add(4); boolean b1 = list.stream().allMatch((n) -> {return n > 8; }); //false boolean b2 = list.stream().anyMatch((n) -> {return n > 8; }); //true boolean b3 = list.stream().noneMatch((n) -> {return n > 8; }); //falseCopy the code
  • The findFirst() method, which gets the first element in the flow
Optional<T> findFirst();
Copy the code

Example:

List<Integer> list = new ArrayList<>(); list.add(13); list.add(12); list.add(8); list.add(4); Optional<Integer> first = list.stream().findFirst(); System.out.println(first.get()); / / 13Copy the code
  • Method findAny(), which returns any random element in the stream
Optional<T> findAny();
Copy the code

Example:

List<Integer> list = new ArrayList<>();
        list.add(12);
        list.add(8);
        list.add(4);
        list.add(13);

        Optional<Integer> any = list.stream().findAny();
        System.out.println(any.get()); 
Copy the code
  • The Max () and min() methods get the largest and smallest elements in the stream
Optional<T> max(Comparator<? super T> comparator);
Optional<T> min(Comparator<? super T> comparator);
Copy the code

Example:

List<Integer> list = new ArrayList<>(); list.add(12); list.add(8); list.add(4); list.add(13); Optional<Integer> max = list.stream().max((n1, n2) -> { return n1 - n2; }); Optional<Integer> min = list.stream().min((n1, n2) -> { return n1 - n2; }); System.out.println(max.get()); //13 System.out.println(min.get()); / / 4Copy the code
  • The reduce() method, which summarizes all the data into one total data
/** * T identity: default * BinaryOperator<T accumulator **/ T identity, BinaryOperator<T> accumulator); Public Interface BinaryOperator<T> extends BiFunction<T,T,T> {} @functionalInterface Public interface  BiFunction<T, U, R> { R apply(T t, U u); }Copy the code

Example:

List<Integer> list = new ArrayList<>(); list.add(12); list.add(8); list.add(4); list.add(13); Integer reduce = list.stream().reduce(0, new BinaryOperator<Integer>() { @Override public Integer apply(Integer integer, Integer integer2) { return integer+integer2; }}); String = list.stream().reduce(0, (n1, n2) -> {return n1 + n2; }); System.out.println(reduce); // 37 = 12 + 8 + 4 + 13Copy the code
  • The mapToInt() method converts an element of type Integer in a Stream to an int
IntStream mapToInt(ToIntFunction<? super T> mapper);
Copy the code

Example:

List<Integer> list = new ArrayList<>();
        list.add(12);
        list.add(8);
        list.add(4);
        list.add(13);
        
list.stream().mapToInt(new ToIntFunction<Integer>() {
            @Override
            public int applyAsInt(Integer value) {
                return value;
            }
        }).forEach(System.out::println);
Copy the code
  • The concat() method, a static method in the Stream interface, merges the two streams
public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
        Objects.requireNonNull(a);
        Objects.requireNonNull(b);

        @SuppressWarnings("unchecked")
        Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>(
                (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator());
        Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel());
        return stream.onClose(Streams.composedClose(a, b));
    }
Copy the code

Example:

List<Integer> list = new ArrayList<>(); list.add(12); list.add(8); list.add(4); list.add(13); Stream<Integer> stream1 = list.stream().filter((str) -> { return str > 12; }); Stream<Integer> stream2 = list.stream().filter((str) -> { return str < 5; }); Stream.concat(stream1, stream2).forEach(System.out::println); / / 13 AprilCopy the code