Cabbage Java self study room covers core knowledge

Java 8 Stream

The Java 8 API has added a new abstraction called a Stream that lets you process data in a declarative way.

Stream provides a high-level abstraction of Java collection operations and expressions in an intuitive manner similar to querying data from a database with SQL statements. The Stream API can greatly improve the productivity of Java programmers, allowing programmers to write efficient, clean, and concise code. This style treats the collection of elements to be processed as a stream that travels through a pipe and can be processed at the nodes of the pipe, such as filtering, sorting, aggregating, and so on. The element stream is processed by intermediate operation in the pipe, and finally the result of the previous processing is obtained by terminal operation.

Stream detail example

1. The forEach loop

@Test
public void forEach(a) {
    You don't bird me, I don't bird you
    List<String> list = Arrays.asList("you"."don't"."bird"."me".","."I"."don't"."bird"."you");

    // Method 1: before JDK1.8 loop mode
    for (String item: list) {
        System.out.println(item);
    }

    // forEach method of Stream
    // void forEach(Consumer<? super T> action)
    list.stream().forEach(item -> System.out.println(item));

    // Method 3: a simplification of method 2
    Since method references are also functional interfaces, method 2 Lambda expressions can also be replaced with method references
    // This method is a short form of method 1 and method 2
    list.stream().forEach(System.out::println);
}
Copy the code

2. The filter to filter

public class User {
    private Long id;
    private String phone;
    private Integer age;

    public User(a) {}
    public User(Long id, String username, Integer age) {
        this.id = id;
        this.username = username;
        this.age = age;
    }
    // Getter & Setter & toString
}


@Test
public void filter(a) {
    List<User> users = Arrays.asList(
            new User(1L."mengday".28),
            new User(2L."guoguo".18),
            new User(3L."liangliang".17));// Stream<T> filter(Predicate<? super T> predicate);
    users.stream().filter(user -> user.getAge() > 18).forEach(System.out::println);
}
Copy the code

3. The map mapping

@Test
public void map(a) {
    List<String> list = Arrays.asList("how"."are"."you"."how"."old"."are"."you"."?");
    // <R> Stream<R> map(Function<? super T, ? extends R> mapper);
    list.stream().map(item -> item.toUpperCase()).forEach(System.out::println);
}
Copy the code

4. flatMap

@Test
public void flatMap(a) {
    List<Integer> a = Arrays.asList(1.2.3);
    List<Integer> b = Arrays.asList(4.5.6);

    // <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
    List<List<Integer>> collect = Stream.of(a, b).collect(Collectors.toList());
    // [[1, 2, 3], [4, 5, 6]] 
    System.out.println(collect);

    // Combine elements from multiple sets into a single set
    List<Integer> mergeList = Stream.of(a, b).flatMap(list -> list.stream()).collect(Collectors.toList());
    // [1, 2, 3, 4, 5, 6]
    System.out.println(mergeList);

    // Build from Builder mode
    Stream<Object> stream = Stream.builder().add("hello").add("hi").add("byebye").build();
}
Copy the code

5. Sorted sequence

@Test
public void sort(a) {
    List<String> list = Arrays.asList("c"."e"."a"."d"."b");
    // Stream<T> sorted(Comparator<? super T> comparator);
    // int compare(T o1, T o2);
    list.stream().sorted((s1, s2) -> s1.compareTo(s2)).forEach(System.out::println);
}
Copy the code

6. Be Specific

@Test
public void distinct(a) {
    Know is know noknow is noknow
    Stream<String> stream = Stream.of("know"."is"."know"."noknow"."is"."noknow");
    stream.distinct().forEach(System.out::println); // know is noknow
}
Copy the code

7. Count Total quantity

@Test
public void count(a) {
    Stream<String> stream = Stream.of("know"."is"."know"."noknow"."is"."noknow");
    long count = stream.count();
    System.out.println(count);
}
Copy the code

8 min and Max

@Test
public void min(a) {
    List<String> list = Arrays.asList("1"."2"."3"."4"."5");
    // Optional<T> min(Comparator<? super T> comparator);
    Optional<String> optional = list.stream().min((a, b) -> a.compareTo(b));
    String value = optional.get();
    System.out.println(value);
}
Copy the code

9. The skip and limit

@Test
public void skip(a) {
    List<String> list = Arrays.asList("a"."b"."c"."d"."e");
    // Stream<T> skip(long n)
    list.stream().skip(2).forEach(System.out::println);  // c, d, e
}

@Test
public void limit(a) {
    List<String> list = Arrays.asList("a"."b"."c"."d"."e");
    list.stream().skip(2).limit(2).forEach(System.out::println);    / / c, d
}
Copy the code

10. collect

@Test
public void collect(a) {
    List<String> list = Arrays.asList("a"."b"."c"."d"."e");
    // Stream -> Collection
    List<String> collect = list.stream().collect(Collectors.toList());

    // Stream -> Object[]
    Object[] objects = list.stream().toArray();
}
Copy the code

11. concat

@Test
public void concat(a) {
    List<String> list = Arrays.asList("a"."b");
    List<String> list2 = Arrays.asList("c"."d");
    Stream<String> concatStream = Stream.concat(list.stream(), list2.stream());
    concatStream.forEach(System.out::println);
}
Copy the code

12. AnyMatch, allMatch

@Test
public void match(a) {
    // You give me stop
    List<String> list = Arrays.asList("you"."give"."me"."stop");
    // boolean anyMatch(Predicate<? super T> predicate);
    // parallelStream can be computed in parallel and is faster than stream
    boolean result = list.parallelStream().anyMatch(item -> item.equals("me"));
    System.out.println(result);
}

/** * anyMatch pseudocode * returns true if one of the elements in the collection meets the criteria@return* /
public boolean anyMatch(a) {
    List<String> list = Arrays.asList("you"."give"."me"."stop");
    for (String item : list) {
        if (item.equals("me")) {
            return true; }}return false;
}
Copy the code

13. The reduce of induction

@Test
public void reduce(a) {
    Stream<String> stream = Stream.of("you"."give"."me"."stop");
    // Optional<T> reduce(BinaryOperator<T> accumulator);
    Optional<String> optional = stream.reduce((before, after) -> before + "," + after);
    optional.ifPresent(System.out::println);    // you,give,me,stop
}

public static void main(String[] args) {
    List<BigDecimal> list = Arrays.asList(
            new BigDecimal("11.11"),
            new BigDecimal("22.22"),
            new BigDecimal("33.33"));/ / 66.66
    BigDecimal sum = list.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
    System.out.println(sum);
}
Copy the code

14. FindFirst, findAny

@Test
public void findFirst(a) {
    Stream<String> stream = Stream.of("you"."give"."me"."stop");
    String value = stream.findFirst().get();
    System.out.println(value);
}

@Test
public void findAny(a) {
    Stream<String> stream = Stream.of("you"."give"."me"."stop");
    String value2 = stream.findAny().get();
    System.out.println(value2);
}
Copy the code