将常量组织起来统一进行管理
场景:错误状态码,消息类型,颜色的划分,状态机等等…
本质:是 java.lang.Enum 的子类,也就是说,自己写的枚举类,就算没有显示的继承 Enum ,但是其默认继承了
这个类。
enum ProgramLanguage {
JAVA,
C,
PYTHON,
PHP,
GO,
}
public static void enumUse(ProgramLanguage language) {
switch (language) {
case JAVA:
System.out.println("JAVA");
break;
case C:
System.out.println("C");
break;
case GO:
System.out.println("GO");
break;
case PHP:
System.out.println("PHP");
break;
case PYTHON:
System.out.println("PYTHON");
break;
}
}
System.out.println(Arrays.toString(ProgramLanguage.values()));
ProgramLanguage language = ProgramLanguage.JAVA;
//
System.out.println(language.ordinal());
ProgramLanguage language1 = ProgramLanguage.valueOf("PYTHON");
System.out.println(language1);
System.out.println(language.compareTo(language1));
基本语法: (parameters) -> expression 或 (parameters) ->{ statements; }
Lambda表达式由三部分组成:
//函数式接口
@FunctionalInterface
interface NoParameterNoReturn {
void test();
}
@FunctionalInterface
interface MoreParameterReturn {
int test(int a, int b);
}
@FunctionalInterface
interface NoParameterReturn {
int test();
}
public class LambdaTest {
public static void main(String[] args) {
//
NoParameterNoReturn noReturn = () -> {
System.out.println("无参无返回值");
};
noReturn.test();
//
MoreParameterReturn moreParameterReturn = (int a,int b) -> {
return a+b;
};
int ret = moreParameterReturn.test(60,70);
System.out.println(ret);
//
NoParameterReturn noParameterReturn = () -> 100;
int ret1 = noParameterReturn.test();
System.out.println(ret1);
}
List<Student> list = new ArrayList<>();
list.add(new Student("Listen", 10, 90));
list.add(new Student("Bike", 20, 91));
list.add(new Student("Franke", 30, 92));
list.add(new Student("Linda", 40, 99));
//for each
for (Student s : list
) {
System.out.print(s + " ");
}
System.out.println();
//
list.forEach(student -> {
System.out.print(student +" ");
});
System.out.println();
//sort()
list.sort((o1, o2) -> o2.age - o1.age);
System.out.println(list);
//map
Map<Integer, String> map = new HashMap<>();
map.put(1, "C");
map.put(2, "Java");
map.put(3, "Python");
map.put(4, "PHP");
//
for (Map.Entry<Integer, String> entry : map.entrySet()
) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
//
map.forEach( (k, v) -> System.out.println(k + "=" + v) );
Lambda表达式的优点很明显,在代码层次上来说,使代码变得非常的简洁。缺点也很明显,代码不易读。