需求:
要求,只能用一行代码实现
现有5个用户,按照以下条件赛选:
1.ID必须是偶数
2.年龄必须大于23岁
3.用户名转为大写字母
4.用户名字倒着排序
5.只输出一个用户
以下是代码示例:
import java.util.Arrays; import java.util.List; public class LinkProgram { public static void main(String[] args) { User u1 = new User(1, "a", 21); User u2 = new User(2, "b", 22); User u3 = new User(3, "c", 23); User u4 = new User(4, "d", 24); User u5 = new User(5, "e", 25); User u6 = new User(6, "f", 26); //List只管存储,计算交给流 List<User> list= Arrays.asList(u1,u2,u3,u4,u5,u6); //计算交给流,java.util.Stream接口 list.stream() .filter(u->{return u.getId()%2==0;}) .filter(u->{return u.getAge()>23;}) .map(u->{return u.getName().toUpperCase();}) .sorted((uu1,uu2)->{return uu2.compareTo(uu1);}) .limit(1) .forEach(System.out::println); } } 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 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; } }
这便是体现流式计算和链式编程的那一行代码
list.stream() .filter(u->{return u.getId()%2==0;}) .filter(u->{return u.getAge()>23;}) .map(u->{return u.getName().toUpperCase();}) .sorted((uu1,uu2)->{return uu2.compareTo(uu1);}) .limit(1) .forEach(System.out::println);
结果
F