1.Lambda表达式
lambda表达式本质上是一段匿名内部类,也可以是一段可以传递的代码
1.1语法
(Type1 param1, Type2 param2, ..., TypeN paramN) ‐> { statment1;
statment2; //............. return statmentM;}
a.绝大多数情况,编译器都可以从上下文环境中推断出lambda表达式的参数类
型,所以参数可以省略:
(param1,param2, ..., paramN) ‐> { statment1; statment2; //............. r
eturn statmentM;}
b.当lambda表达式的参数个数只有一个,可以省略小括号:
param1 ‐> { statment1; statment2; //............. return statmentM;}
c.当lambda表达式只包含一条语句时,可以省略大括号、return和语句结尾的
分号:
param1 ‐> statment
()-> System.out.println("这是简略模式")
1.2函数接口
函数接口是只有一个抽象方法的接口,可以有default和static方法 ,用作 Lambda 表达式的返回类型。接口类上面都有@FunctionalInterface这个注解。
1.3常用的函数式接口举例
a.Supplier接口,get方法
private static String newString(Supplier<String> supplier){
return supplier.get();
}
public static void main(String[] args) {
String str1 = newString(()->"朴初珑");
System.out.println(str1);
int arr[]={1,22,33,44,231,423,11,256,666,888,251,521};
int max = getMax(()->{
int rtn =arr[0];
for(int i:arr){
if(i>rtn){
rtn=i;
}
}
return rtn;
});
System.out.println(max);
}
private static Integer getMax(Supplier<Integer> supplier){
return supplier.get();
}
b.Consumer<T> accept方法
public static void main(String[] args) {
consumer("麻黄",something-> System.out.println(something+"汤一碗"));
doubleConsumer("麻黄",some-> System.out.println("华佗用"+some+"开出"),some-> System.out.println(some+"汤一碗"));
}
private static void consumer(String something, Consumer<String> consumer){
consumer.accept(something);
}
private static void doubleConsumer(String something,Consumer<String> consumer1,Consumer<String> consumer2){
consumer1.andThen(consumer2).accept(something);
}
c.Predicate<T> test判断方法
public static void main(String[] args) {
String something1="朴初珑";
String something2="迪丽热巴";
boolean heathy = predicate("朴初珑",some->some.equals(something1));
System.out.println(heathy);
boolean healthyAnd = andPredicate("迪丽热巴",some->some.equals(something1),some->some.equals(something2));
System.out.println(healthyAnd);
boolean healthyOr = orPredicate("朴初珑",some->some.equals(something1),some->some.equals(something2));
System.out.println(healthyOr);
}
private static boolean predicate(String something, Predicate<String> predicate){
return predicate.test(something);
}
private static boolean andPredicate(String something, Predicate<String> predicate1,Predicate<String> predicate2){
return predicate1.and(predicate2).test(something);
}
private static boolean orPredicate(String something, Predicate<String> predicate1,Predicate<String> predicate2){
return predicate1.or(predicate2).test(something);
}
private static boolean negPredicate(String something, Predicate<String> predicate){
return predicate.negate().test(something);
}
d.Function<T, R>,apply(T t)转换方法
public static void main(String[] args) {
int i = function("666",some->Integer.parseInt(some));
System.out.println(i);
i=andFunction("100",some->Integer.parseInt(some),some->some/10);
System.out.println(i);
}
private static Integer function(String something, Function<String,Integer> function){
return function.apply(something);
}
private static Integer andFunction(String something,Function<String,Integer> function,Function<Integer,Integer> function2){
return function.andThen(function2).apply(something);
}
1.4lambda例子
public class Test {
private static Comparator<Integer> comparator(){
return new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1,o2);
}
};
}
private static Comparator<Integer> comparator1(){
return ((o1, o2) -> Integer.compare(o2,o1));
}
public static void main(String[] args) {
Comparator<Integer> cpt = comparator();
TreeSet<Integer> set = new TreeSet<>(cpt);
set.add(1);
set.add(3);
set.add(2);
set.add(100);
System.out.println(set);
System.out.println("====================");
Comparator<Integer> cpt1 = comparator1();
TreeSet<Integer> set1 = new TreeSet<>(cpt1);
set1.add(1);
set1.add(3);
set1.add(2);
set1.add(100);
System.out.println(set1);
}
}
2.方法引用
基本格式就是:方法的调用者(大多为类):方法 ,方法的引用就是一种特殊的lambda表达式。
public static void main(String[] args) {
Consumer<Integer> con = x-> System.out.println(x);
con.accept(100);
Consumer<Integer> con1 = System.out::println;
con1.accept(666);
BiFunction<Integer,Integer,Integer> biFun =(a,b)->Integer.compare(a,b);
System.out.println(biFun.apply(1,2));
BiFunction<Integer,Integer,Integer> biFun2 = Integer::compareTo;
System.out.println(biFun2.apply(3,4));
BiFunction<String,String,Boolean> biFun3 =(a,b)->a.equals(b);
BiFunction<String,String,Boolean> biFun4 =String::equals;
System.out.println(biFun3.apply("1","2"));
System.out.println(biFun4.apply("2","2"));
}
3.流
栗子:
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("朴初珑");
list.add("迪丽热巴");
list.add("高圆圆");
for (String s : list) {
if(s.startsWith("朴")&&s.length()==3){
System.out.println("老婆加一:"+s);
}
}
list.stream().filter(s->s.startsWith("朴")).filter(s -> s.length()==3).forEach(System.out::println);
}
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Stream<String> stream1 = list.stream();
Set<String> set = new HashSet<>();
Stream<String> stream2 = set.stream();
Map<String,Integer> map = new HashMap<>();
Set<String> key = map.keySet();
Stream<String> stream = key.stream();
Collection<Integer> values = map.values();
Stream<Integer> stream3 = values.stream();
Stream<Integer> arrayStream = Stream.of(1,66,999);
String[] wifes = {"朴初珑","迪丽热巴","杨幂"};
Stream<String> stream4 = Stream.of(wifes);
}
}
次例为将各个集合转换为steam流
public class Test {
public static void main(String[] args) {
Stream<String> str = Stream.of("朴初珑","迪丽热巴","杨幂");
str.forEach(s-> System.out.println("我的老婆有:"+s));
Stream<String> str1 = Stream.of("66","6","999","1");
str1.map(Integer::parseInt).forEach(System.out::println);
System.out.println("=====================================");
Stream<String> str2 = Stream.of("66","6","999","1");
str2.map(Integer::parseInt).limit(3).forEach(System.out::println);
System.out.println("======================================");
Stream<String> str3 = Stream.of("66","6","999","1");
str3.map(Integer::parseInt).limit(3).skip(2).forEach(System.out::println);
System.out.println("========================================");
Stream.concat(Stream.of(1,2,3),Stream.of(4,5,6)).forEach(System.out::println);
}
}
次例中通过Stream.concat()将两个流合并为一个流
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7);
Integer count = list.stream().reduce(1,(x,y)->x+y);
System.out.println(count);
List<Integer> ageList = list.stream().collect(Collectors.toList());
ageList.stream().forEach(System.out::println);
}
4.新的日期
日期:
public class Test {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(today);
LocalDate oldDate = LocalDate.of(2020,5,1);
System.out.println(oldDate);
LocalDate oldDate1 = LocalDate.parse("2020-07-31");
System.out.println(oldDate1);
//本月第一天
LocalDate firstMonthOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth());
System.out.println(firstMonthOfThisMonth);
//取本月第二天
LocalDate secondDayOfThisMonth = today.withDayOfMonth(2);
System.out.println(secondDayOfThisMonth);
//取本月最后一天
LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDayOfThisMonth);
//取本月最后一天的下一天
LocalDate nextDay = lastDayOfThisMonth.plusDays(1);
System.out.println(nextDay);
//取今年12月第一个周三
LocalDate date = LocalDate.parse("2021-12-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.WEDNESDAY));
System.out.println(date);
}
}
时间:
public class Test {
public static void main(String[] args) {
//会返回到纳秒值
LocalTime todayTime = LocalTime.now();
System.out.println(todayTime);
//不会返回纳秒值
LocalTime todayTime1= LocalTime.now().withNano(0);
System.out.println(todayTime1);
LocalTime time = LocalTime.parse("10:53:30");
System.out.println(time);
//转化为时间戳
long time1 = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println(time1);
long time2 = System.currentTimeMillis();
System.out.println(time2);
//将时间戳转化为localdatetime
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss.SSS");
String format = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time1), ZoneId.of("Asia/Shanghai")));
System.out.println(format);
}
}
注意:时间转换格式大小写必须这样YYYY-MM-dd HH:mm:ss.SSS,否则时间会错乱
public class Test {
public static void main(String[] args) {
new Test().test03();
}
//格式化时间
public void test01(){
LocalDateTime d1 = LocalDateTime.now();
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String s1 = d1.format(df);
String s2 = df.format(d1);
System.out.println(s1);
System.out.println(s2);
}
//使用api转换接口
public void test02(){
DateTimeFormatter df = DateTimeFormatter.ISO_DATE;
LocalDateTime d1 = LocalDateTime.now();
System.out.println(df.format(d1));
}
//获取下一个工作日
public void test03(){
LocalDateTime d = LocalDateTime.now();
LocalDateTime day = d.with((t)->{
LocalDateTime d1 = (LocalDateTime) t;
DayOfWeek dow = d1.getDayOfWeek();
if(dow.equals(DayOfWeek.FRIDAY)){
return d1.plusDays(3);
}else if(dow.equals(DayOfWeek.SATURDAY)){
return d1.plusDays(2);
}else{
return d1.plusDays(1);
}
});
System.out.println(day);
}
}