首先体会一下链式编程
@AllArgsConstructor
@NoArgsConstructor
@Data
@Accessors(chain = true)
public class Book {
private int id;
private String name;
private double prize;
public static void main(String[] args) {
Book book = new Book();
book.setId(10).setName("java").setPrize(20.5d);
}
}
链式编程在于返回值还是当前对象
认识 流式计算
集合讲的是数据,流讲的是计算
题目:请按照给出的数据,找出同时满足以下条件的用户,
1 偶数Id 且年龄大于24 且用户名转为大写倒着排序
2 只输出一个用户的名字
public class Test {
public static void main(String[] args) {
User u1 = new User(1,"a",22);
User u2 = new User(2,"b",23);
User u3 = new User(3,"c",24);
User u4 = new User(4,"d",25);
User u5 = new User(6,"e",26);
// 集合就是存储
List<User> list = Arrays.asList(u1, u2, u3, u4, u5);
// 计算交给Stream流
// lambda表达式、链式编程、函数式接口、Stream流式计算
list.stream()
.filter(u-> u.getId()%2==0)
.filter(u-> u.getAge()>24)
.map(u-> u.getName().toUpperCase())
.sorted((uu1,uu2)-> uu2.compareTo(uu1))
.limit(1)
.forEach(System.out::println);
List<Integer> list2 = Arrays.asList(1,2,3,4,5);
list2 = list2.stream().map(x -> x*2).collect(Collectors.toList());//映射然后转换成list
list2.forEach(System.out::println);
}
}