Stream computing in java

What exactly is a stream?

Is a data channel, used to manipulate the sequence of elements generated by the data source (collection, array, etc.).

The collection is about data, and the stream is aboutCalculation

Features

  1. Stream itself does not store elements
  2. Stream does not change the source object. Instead, they will return a new Stream holding the result.
  3. Stream operations are executed delayed. This means they will wait until results are needed before executing.

stage

  1. Create a Stream: a data source (array, collection)
  2. Intermediate operation: an intermediate operation, processing data source data
  3. Termination operation: a termination operation that executes an intermediate chain of operations and produces results

Source => Intermediate Pipeline => Results

map: map

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

@Data
@NoArgsConstructor
@AllArgsConstructor
class User {
    
    
    private Integer id;
    private String  userName;
    private int     age;
}
/**
 * @author shenguangyang
 * 题目:请按照给出数据,找出同时满足
 *      偶数ID且年龄大于24且用户名转为大写且用户名字母倒排序
 *      最后只输出一个用户名字
 */
public class StreamDemo {
    
    
    public static void main(String[] args) {
    
    
        User u1 = new User(11,"a",23);
        User u2 = new User(12,"b",24);
        User u3 = new User(13,"c",22);
        User u4 = new User(14,"d",28);
        User u5 = new User(16,"e",26);
        List<User> users = Arrays.asList(u1, u2, u3, u4, u5);

        users.stream().filter(u -> {
    
    
            return u.getAge() % 2 == 0;
        }).filter(u -> {
    
    
            return u.getAge() > 24;
        }).map(u -> {
    
    
            return u.getUserName().toUpperCase();
        }).sorted((o1,o2) -> {
    
    
            return o2.compareTo(o1);
        }).limit(1).forEach(System.out::println);

        //R apply(T t);函数型接口,一个参数,一个返回值
        Function<String,Integer> function = s -> s.length();
        System.out.println(function.apply("abc"));

        //boolean test(T t);断定型接口,一个参数,返回boolean
        Predicate<String> predicate = s -> {
    
    
            return s.startsWith("a");
        };
        System.out.println(predicate.test("abc"));

        // void accept(T t);消费型接口,一个参数,没有返回值
        Consumer<String> consumer = s -> System.out.println(s);
        consumer.accept("123123");

        // T get(); 供给型接口,无参数,有返回值
        Supplier<String> supplier = () -> "返回值";
        System.out.println(supplier.get());
    }
}

Guess you like

Origin blog.csdn.net/weixin_43088443/article/details/112799735