新时代程序员必须掌握:lambda 表达式、链式编程、函数式接口、Stream 流式计算
为什么要使用流式计算?
大数据: 存储+计算 集合、MySQL本质就是存储东西的; 计算都应该交给流来操作!
现在通过下面的题来了解链式编程。
/** * 题目要求:现在有5个用户!筛选; * 1、ID 必须是偶数 * 2、年龄必须大于23岁 * 3、用户名转为大写字母 * 4、用户名字母倒着排序 * 5、只输出一个用户! */ @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; }
filter(完成id是偶数,年龄大于23的过滤)
public class StreamExample { public static void main(String[] args) { User user1 = new User(1, "a", 21); User user2 = new User(2, "b", 26); User user3 = new User(3, "c", 23); User user4 = new User(4, "d", 24); User user5 = new User(5, "e", 25); List<User> list = Arrays.asList(user1, user2, user3, user4, user5); //流式计算 list.stream() .filter(user -> {return user.getId()%2 == 0;}) .filter(user -> {return user.getAge()>23;}) .forEach(System.out::println); } }
结果如下 User(id=2, name=b, age=26) User(id=4, name=d, age=24)
map 输出的名字大写
public class StreamExample { public static void main(String[] args) { User user1 = new User(1, "a", 21); User user2 = new User(2, "b", 26); User user3 = new User(3, "c", 23); User user4 = new User(4, "d", 24); User user5 = new User(5, "e", 25); List<User> list = Arrays.asList(user1, user2, user3, user4, user5); //流式计算 list.stream() .filter(user -> {return user.getId()%2 == 0;}) .filter(user -> {return user.getAge()>23;}) .map(user -> {return user.getName().toUpperCase();}) .forEach(System.out::println); } }
结果 B D
sorted 用sorted完成倒序(默认是顺序)
Comparable
,一个java.lang.ClassCastException
执行终端操作时,可以抛出。public class StreamExample { public static void main(String[] args) { User user1 = new User(1, "a", 21); User user2 = new User(2, "b", 26); User user3 = new User(3, "c", 23); User user4 = new User(4, "d", 24); User user5 = new User(5, "e", 25); List<User> list = Arrays.asList(user1, user2, user3, user4, user5); //流式计算 list.stream() .filter(user -> {return user.getId()%2 == 0;}) .filter(user -> {return user.getAge()>23;}) .map(user -> {return user.getName().toUpperCase();}) .sorted((u1,u2)->{return u2.compareTo(u1);}) .forEach(System.out::println); } }
结果 D B
limit 只输出一个用户
maxSize
。public class StreamExample { public static void main(String[] args) { User user1 = new User(1, "a", 21); User user2 = new User(2, "b", 26); User user3 = new User(3, "c", 23); User user4 = new User(4, "d", 24); User user5 = new User(5, "e", 25); List<User> list = Arrays.asList(user1, user2, user3, user4, user5); //流式计算 list.stream() .filter(user -> {return user.getId()%2 == 0;}) .filter(user -> {return user.getAge()>23;}) .map(user -> {return user.getName().toUpperCase();}) .sorted((u1,u2)->{return u2.compareTo(u1);}) .limit(1) .forEach(System.out::println); } }
结果 D
参考教程:https://www.kuangstudy.com/