stream(流) 截取list的几个

list的几个截取对象

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

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    // 名字
    private String name;
    // 年龄
    private Integer age;
    // 性别
    private String sex;

}

main


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamMain {

    public static void main(String[] args) {
        List<User> userList = new ArrayList();
        userList.add(new User("张1", 12, "男"));
        userList.add(new User("张2", 20, "女"));
        userList.add(new User("张3", 18, "男"));
        userList.add(new User("张4", 24, "女"));
        userList.add(new User("张5", 16, "男"));

        //截userlist的前3个
        List<User> collect2 = userList.stream().limit(3).collect(Collectors.toList());
        System.out.println(collect2);

    }


}

结果

[User(name=1, age=12, sex=), User(name=2, age=20, sex=), User(name=3, age=18, sex=)]

你可能感兴趣的:(java,list)