1.创建一个实体类User包含属性主键id,姓名,密码
public class User {
private Integer id;
private String name;
private String pwd;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public User(Integer id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
2.流中元素的操作
(1)stream流中map是用于对流中元素的转换。
(2)filter对流中的元素做了一个筛选。
(3)sorted对流中的元素进行排序。
(4)limit skip限制流的数量。
public static void main(String[] args) {
List<User> users=new ArrayList<>();
users.add(new User(1,"张三","123"));
users.add(new User(3,"李四","666"));
users.add(new User(3,"李四","666"));
users.add(new User(6,"孙六","789"));
users.add(new User(8,"赵八","888"));
users.add(new User(2,"钱九","666"));
//map是用于对流中元素的转换
List<Integer> collect = users.stream().map(User::getId).collect(Collectors.toList());
List<String> collect1 = users.stream().map(User::getName).collect(Collectors.toList());
collect.forEach(System.out::print);
System.out.println("--------------");
collect1.forEach(System.out::print);
//filter对流中的元素做了一个筛选
List<User> users1 = users.stream().filter(user -> user.getId() > 3).collect(Collectors.toList());
System.out.println("--------------");
users1.forEach(System.out::print);
//sorted对流中的元素进行排序
List<Integer> ids = collect.stream().sorted().collect(Collectors.toList());
System.out.println("--------------");
ids.forEach(System.out::print);
//distinct用于去除重复的元素
List<Integer> userid = ids.stream().distinct().collect(Collectors.toList());
System.out.println("--------------");
userid.forEach(System.out::print);
//limit skip限制流的数量
List<Integer> limit = ids.stream().limit(3).collect(Collectors.toList());
System.out.println("--------------");
limit.forEach(System.out::print);
List<Integer> skip = ids.stream().skip(4).collect(Collectors.toList());
System.out.println("--------------");
skip.forEach(System.out::print);
}