Java8 新特性
Java8 新特性
1.Interface
新 interface 的方法可以用default
或 static
修饰,这样就可以有方法体,实现类也不必重写此方法
default
修饰的方法,是普通实例方法,可以用this
调用,可以被子类继承、重写。static
修饰的方法,使用上和一般类静态方法一样。但它不能被子类继承,只能用Interface
调用
public interface InterfaceNew {static void sm() {System.out.println("interface提供的方式实现");}static void sm2() {System.out.println("interface提供的方式实现");}default void def() {System.out.println("interface default方法");}default void def2() {System.out.println("interface default2方法");}//须要实现类重写void f();
}public interface InterfaceNew1 {default void def() {System.out.println("InterfaceNew1 default方法");}
}//
public class InterfaceNewImpl implements InterfaceNew , InterfaceNew1{public static void main(String[] args) {InterfaceNewImpl interfaceNew = new InterfaceNewImpl();interfaceNew.def();}@Overridepublic void def() {InterfaceNew1.super.def();}@Overridepublic void f() {}
}
2.functional interface 函数式接口
3.Lambda 表达式
格式
(parameters) -> expression 或
(parameters) ->{ statements; }
3.1替代匿名内部类
1.Runnable
接口
2.Comparator
接口
3.Listener
接口
4.自定义接口
@FunctionalInterface
public interface LambdaInterface {void f();
}
//使用
public class LambdaClass {public static void forEg() {lambdaInterfaceDemo(()-> System.out.println("自定义函数式接口"));}//函数式接口参数static void lambdaInterfaceDemo(LambdaInterface i){i.f();}
}
3.2集合迭代
void lamndaFor() {List<String> strings = Arrays.asList("1", "2", "3");//传统foreachfor (String s : strings) {System.out.println(s);}//Lambda foreachstrings.forEach((s) -> System.out.println(s));//orstrings.forEach(System.out::println);//mapMap<Integer, String> map = new HashMap<>();map.forEach((k,v)->System.out.println(v));
}
3.3方法的引用
public class LambdaClassSuper {LambdaInterface sf(){return null;}
}public class LambdaClass extends LambdaClassSuper {public static LambdaInterface staticF() {return null;}public LambdaInterface f() {return null;}void show() {//1.调用静态函数,返回类型必须是functional-interfaceLambdaInterface t = LambdaClass::staticF;//2.实例方法调用LambdaClass lambdaClass = new LambdaClass();LambdaInterface lambdaInterface = lambdaClass::f;//3.超类上的方法调用LambdaInterface superf = super::sf;//4. 构造方法调用LambdaInterface tt = LambdaClassSuper::new;}
}
3.4访问变量
int i = 0;
Collections.sort(strings, (Integer o1, Integer o2) -> o1 - i);
//i =3;lambda 表达式可以引用外边变量,但是该变量默认拥有 final 属性
4.Stream
@Test
public void test() {List<String> strings = Arrays.asList("abc", "def", "gkh", "abc");//返回符合条件的streamStream<String> stringStream = strings.stream().filter(s -> "abc".equals(s));//计算流符合条件的流的数量long count = stringStream.count();//forEach遍历->打印元素strings.stream().forEach(System.out::println);//limit 获取到1个元素的streamStream<String> limit = strings.stream().limit(1);//toArray 比如我们想看这个limitStream里面是什么,比如转换成String[],比如循环String[] array = limit.toArray(String[]::new);//map 对每个元素进行操作返回新流Stream<String> map = strings.stream().map(s -> s + "22");//sorted 排序并打印strings.stream().sorted().forEach(System.out::println);//Collectors collect 把abc放入容器中List<String> collect = strings.stream().filter(string -> "abc".equals(string)).collect(Collectors.toList());//把list转为string,各元素用,号隔开String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(","));//对数组的统计,比如用List<Integer> number = Arrays.asList(1, 2, 5, 4);IntSummaryStatistics statistics = number.stream().mapToInt((x) -> x).summaryStatistics();System.out.println("列表中最大的数 : "+statistics.getMax());System.out.println("列表中最小的数 : "+statistics.getMin());System.out.println("平均数 : "+statistics.getAverage());System.out.println("所有数之和 : "+statistics.getSum());//concat 合并流List<String> strings2 = Arrays.asList("xyz", "jqx");Stream.concat(strings2.stream(),strings.stream()).count();//注意 一个Stream只能操作一次,不能断开,否则会报错。Stream stream = strings.stream();//第一次使用stream.limit(2);//第二次使用stream.forEach(System.out::println);//报错 java.lang.IllegalStateException: stream has already been operated upon or closed//但是可以这样, 连续使用stream.limit(2).forEach(System.out::println);
}
5.Optional
class Zoo {private Dog dog;
}class Dog {private int age;
}Zoo zoo = getZoo();
if(zoo != null){Dog dog = zoo.getDog();if(dog != null){int age = dog.getAge();System.out.println(age);}
}Optional.ofNullable(zoo).map(o -> o.getDog()).map(d -> d.getAge()).ifPresent(age ->System.out.println(age)
);
6.Date-Time API
LocalDateTime.class //日期+时间 format: yyyy-MM-ddTHH:mm:ss.SSS
LocalDate.class //日期 format: yyyy-MM-dd
LocalTime.class //时间 format: HH:mm:ss
Java 8 之前:
public void oldFormat(){Date now = new Date();//format yyyy-MM-ddSimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String date = sdf.format(now);System.out.println(String.format("date format : %s", date));//format HH:mm:ssSimpleDateFormat sdft = new SimpleDateFormat("HH:mm:ss");String time = sdft.format(now);System.out.println(String.format("time format : %s", time));//format yyyy-MM-dd HH:mm:ssSimpleDateFormat sdfdt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String datetime = sdfdt.format(now);System.out.println(String.format("dateTime format : %s", datetime));
}
Java 8 之后:
public void newFormat(){//format yyyy-MM-ddLocalDate date = LocalDate.now();System.out.println(String.format("date format : %s", date));//format HH:mm:ssLocalTime time = LocalTime.now().withNano(0);System.out.println(String.format("time format : %s", time));//format yyyy-MM-dd HH:mm:ssLocalDateTime dateTime = LocalDateTime.now();DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String dateTimeStr = dateTime.format(dateTimeFormatter);System.out.println(String.format("dateTime format : %s", dateTimeStr));
}
Java 8 之前 转换都需要借助 SimpleDateFormat
类,而Java 8 之后只需要 LocalDate
、LocalTime
、LocalDateTime