枚举
通过一个标识符,标识一些值。为了避免某些值不能随便填
枚举定义
public enum Gender {
Male, Female;
}
枚举使用
public class GenderTest {
public static void main(String[] args) {
// Gender gender = Gender.Female;
Student student = new Student();
student.setGender(Gender.Female);
}
}
注解
能够将注解写到: 类头部、接口头部、枚举头部、注解头部、方法头部、成员变量头部、构造器头部、参数头部
注解与注释的区别:
注解是写给程序看的
注释是写给人看的
注解定义
public @interface MyAnnotation {
// 凡是注解,必然有一个value属性
// MyAnnotation中可以有多个属性
// 当使用此注解时,如果只指定value属性,那么`value=`不用写
public String value() default "12345";
public String name() default "zhangsan";
}
注解解析
public class MyAnnotationParser {
public static void main(String[] args) throws ClassNotFoundException {
TypeAnnotationsScanner typeAnnotationsScanner = new TypeAnnotationsScanner();
Reflections reflections = new Reflections("com.mobiletrain", typeAnnotationsScanner);
// 想要知道哪些类使用MyAnnotation描述了
Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(MyAnnotation.class);
System.out.println();
}
}
Stream API
概述
Stream直译: 流
流式操作
- 创建Stream
- 中间操作
- 终止
流式写法
一直.方法().方法().方法()
API概览
创建Stream
- 通过Collection对象的steram()或parallelStream()方法
- 通过Arrays类的steram()方法
- 通过Stream接口的of()、iterate()、generate()方法。
- 通过IntStream、LongStream、DoubleStream接口中的of、range、rangeCLosed方法。
中间操作
- filter
过滤
- limit
- skip
- distinct
- sorted
排序
- map
- parallel
终止操作
- forEach
遍历
- min
- max
- count
统计
- reduce
- collect
收集
快速入门
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("1", "张三", "123456", 99));
students.add(new Student("2", "李四", "234567", 60));
students.add(new Student("3", "王五", "345678", 59));
students.add(new Student("4", "赵六", "654321", 20));
students.add(new Student("5", "田七", "987654", 100));
// 1. 创建Stream对象
Stream<Student> stream = students.stream();
// 2. 中间操作
// 查看所有已及格的学生名字
Stream<Student> studentStream = stream.filter((student) -> student.getScore() >= 60);
// 将所有已经过滤之后的所有学生
// 根据分数排序
Stream<Student> sorted = studentStream.sorted((o1, o2) -> {
return o1.getScore() - o2.getScore();
});
// 3. 终止
// 1. 统计Stream之后的学生个数
// long count = sorted.count();
// 2. 遍历并且输出这些学生的姓名
// sorted.forEach(student -> {
// System.out.println(student.getUsername());
// });
// 3. 将Stream结束之后的元素,封闭为一个List
List<Student> collect = sorted.collect(Collectors.toList());
System.out.println();
}
优化
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("1", "张三", "123456", 99));
students.add(new Student("2", "李四", "234567", 60));
students.add(new Student("3", "王五", "345678", 59));
students.add(new Student("4", "赵六", "654321", 20));
students.add(new Student("5", "田七", "987654", 100));
List<Student> collect = students
.stream()
.filter((student) -> student.getScore() >= 60)
.sorted((o1, o2) -> o1.getScore() - o2.getScore())
.collect(Collectors.toList());
System.out.println();
}