1、Lambda 表达式
Lambda 表达式主要用来定义行内执行的方法类型接口,且免去了使用匿名方法的麻烦。
public class Test {
public static void main(String args[]){
Test tester = new Test();
// 类型声明
MathOperation addition = (int a, int b) -> a + b;
// 不用类型声明
MathOperation subtraction = (a, b) -> a - b;
// 大括号中的返回语句
MathOperation multiplication = (int a, int b) -> { return a * b; };
// 没有大括号及返回语句
MathOperation division = (int a, int b) -> a / b;
System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + tester.operate(10, 5, division));
// 不用括号
GreetingService greetService1 = message -> System.out.println("Hello " + message);
// 用括号
GreetingService greetService2 = (message) -> System.out.println("Hello " + message);
greetService1.sayMessage("小明");
greetService2.sayMessage("小黄");
}
interface MathOperation { int operation(int a, int b); }
interface GreetingService { void sayMessage(String message); }
private int operate(int a, int b, MathOperation mathOperation){ return mathOperation.operation(a, b); }
}
输出结果:
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello 小明
Hello 小黄
2、方法引用
方法引用通过方法的名字来指向一个方法
格式:类名::方法名
public class Test {
public static void main(String args[]){
Person [] persons = new Person[10];
// ------------引用静态方法-------------
//使用匿名类
Arrays.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.birthday.compareTo(o2.birthday);
}
});
//使用lambda表达式
Arrays.sort(persons, (o1, o2) -> o1.birthday.compareTo(o2.birthday));
//使用lambda表达式和类的静态方法
Arrays.sort(persons, (o1, o2) -> Person.compareByAge(o1,o2));
//使用方法引用,引用的是类的静态方法
Arrays.sort(persons, Person::compareByAge);
// ------------引用对象的实例方法-------------
Helper helper = new Helper();
//使用lambda表达式,对象的实例方法
Arrays.sort(persons,(a,b)->helper.compareByAge(a,b));
//使用方法引用,引用的是对象的实例方法
Arrays.sort(persons, helper::compareByAge);
// ------------引用类型对象的实例方法------------
String[] stringsArray = {"Hello","World"};
//使用lambda表达式和类型对象的实例方法
Arrays.sort(stringsArray,(s1,s2)->s1.compareToIgnoreCase(s2));
//使用方法引用,引用的是类型对象的实例方法
Arrays.sort(stringsArray, String::compareToIgnoreCase);
// ------------引用构造方法------------
Supplier<Person> p = Person::new;
Person person = p.get();
// ------------传递参数------------
List<String> al = Arrays.asList("a", "b", "c", "d");
al.forEach(Helper::printString);
//下面的方法和上面等价的
Consumer<String> methodParam = Helper::printString; //方法参数
al.forEach(x -> methodParam.accept(x));//方法执行accept
}
}
class Helper{
public int compareByAge(Person a,Person b){
return a.getBirthday().compareTo(b.getBirthday());
}
public static void printString(String str){
System.out.print(str + " ");
}
}
class Person {
public enum Sex{ MALE,FEMALE }
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public Person() {
this.name = "小明";
}
public String getEmailAddress() { return emailAddress; }
public Sex getGender() { return gender; }
public LocalDate getBirthday() { return birthday; }
public String getName() { return name; }
public static int compareByAge(Person a,Person b){ return a.birthday.compareTo(b.birthday); }
}
3、函数式接口
有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
public class Test {
public static void main(String args[]) {
Service service = message -> System.out.println("Hello " + message);
service.sayMessage("小明");
}
}
@FunctionalInterface
interface Service {
void sayMessage(String message);
}
4、默认方法
默认方法就是接口可以有实现方法,而且不需要实现类去实现其方法。在方法名前面加default 关键字即可实现默认方法。
interface Test {
default void print(){
System.out.println("我是一个默认方法!");
}
}
5、Stream
stream–>filter–>sorted–>map–>collect
生成流:stream() − 为集合创建串行流
parallelStream() − 为集合创建并行流
forEach:迭代流中的每个数据
map:映射每个元素到对应的结
filter:通过设置的条件过滤出元素
limit:获取指定数量的流
sorted:对流进行排序
Collectors:归约操作
统计:用于int、double、long等基本类型
public class Test {
public static void main(String args[]) {
List<String> strings = Arrays.asList("1", "", "21", "123", "2224", "", "115", "");
List<Integer> integers = Arrays.asList(1,2,3,4,5);
System.out.println("空字符串数量为: " + strings.stream().filter(s -> s.isEmpty()).count());
System.out.println("字符串长度为3的数量为: " + strings.stream().filter(s -> s.length() == 3).count());
System.out.println("筛选不为空后的列表: " +strings.stream().filter(s->!s.isEmpty()).collect(Collectors.toList()));
System.out.println("合并字符串: " + strings.stream().filter((s -> !s.isEmpty())).collect(Collectors.joining(",")));
System.out.println("Squares List: " + integers.stream().map(i->i*i).collect(Collectors.toList()));
IntSummaryStatistics stats = integers.stream().mapToInt(i ->i).summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());
Random r = new Random();
System.out.println("随机数: ");
r.ints(1,20).limit(10).sorted().forEach(System.out::println);
System.out.println("---------");
r.ints(5,1,20).forEach(System.out::println);
}
}
6、日期时间
本地化日期时间
public class Test {
public static void main(String args[]) {
// 获取当前的日期时间
LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);
LocalDate date = currentTime.toLocalDate();
System.out.println("date: " + date);
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
System.out.println("月: " + month +" 日: " + day +" 秒: " + seconds);
LocalDateTime date1 = currentTime.withDayOfMonth(10).withYear(2012);
System.out.println("date1: " + date1);
LocalDate date2 = LocalDate.of(2014, Month.DECEMBER, 12);
System.out.println("date2: " + date2);
LocalTime date3 = LocalTime.of(22, 15);
System.out.println("date3: " + date3);
// 解析字符串
LocalTime date4 = LocalTime.parse("20:15:30");
System.out.println("date4: " + date4);
}
}
使用时区的日期时间
public class Test {
public static void main(String args[]) {
// 获取当前时间日期
ZonedDateTime date1 = ZonedDateTime.parse("2019-06-03T10:15:30+05:30[Asia/Shanghai]");
System.out.println("date1: " + date1);
ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("当期时区: " + currentZone);
}
}