Version: Next

Stream流式计算

详细进阶用法

  • 存储
    • 集合、数据库
  • 计算

java.util.Stream

  • stream()——将一个集合转换为流
  • filter(Predicate)——过滤
  • map(Function)
  • sorted(Comparator)——排序
  • limit(long)——分页
  • User Pojo
public class User {
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

例1

题目:

要求:一分钟内完成,只用一行代码

  • 现有5个用户,对其进行筛选
  • ID必须是偶数
  • 年龄必须大于23
  • 用户名转为大写字母
  • 用户名字母倒着排序
  • 只能输出一个用户
@Test
public void test() {
User user1 = new User(1, "a", 21);
User user2 = new User(2, "b", 22);
User user3 = new User(3, "c", 23);
User user4 = new User(4, "d", 24);
User user6 = new User(6, "f", 2
List<User> users = Arrays.asList(user1, user2, user3, user4, user5, user6);
// your code
// your code
}
@Test
public void test() {
User user1 = new User(1, "a", 21);
User user2 = new User(2, "b", 22);
User user3 = new User(3, "c", 23);
User user4 = new User(4, "d", 24);
User user5 = new User(5, "e", 25);
User user6 = new User(6, "f", 26);
List<User> users = Arrays.asList(user1, user2, user3, user4, user5, user6);
// your code
users.stream()
.filter((user) -> {return user.getId() % 2 == 0;})
.filter((user) -> {return user.getAge() > 23;})
.map((user -> user.getName().toUpperCase()))
.sorted((o1, o2) -> {return o2.compareTo(o1);})
.limit(1)
.forEach(System.out::println);
// your code
}

例2

为了构建树形结构,将实体类集合体变为实体节点类集合

  • 实体类集合进行流式操作
  • 采用map操作,来完成实体类对象实体节点类对象的映射
  • 使用BeanUtils.copyProperties(source, target),把source中的属性,复制到target的属性上
  • 使用collect方法,传入参数为Collector.toList(),把映射的结果捣鼓为一个集合返回
List<SysOrgNode> sysOrgNodes = sysOrgs.stream().map(item -> {
SysOrgNode bean = new SysOrgNode();
BeanUtils.copyProperties(item, bean);
return bean;
}).collect(Collectors.toList());