一,jdk 1.7
1,在Switch中可用String
2,数字字面量可以使用下划线,下划线不能在开头和结尾,不能在小数点前后
例:int t=111_33;
3,编译器能够从上下文推断出参数类型
例:List<String> list = new ArrayList<>();
4,对于实现AutoCloseable的类,使用try-with-resources语法可以自动关闭资源。
public static void main(String[] args) {
try (
BufferedReader in = new BufferedReader(new FileReader("in.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"))
) {
/*代码块*/
} catch (Exception e) {
e.printStackTrace();
}
}
二,jdk 1.8
1,接口中可以定义默认实现方法和静态方法
public interface test {
default void a(){
}
static void b(){
}
}
2,Lambda 表达式
List<String> a = Arrays.asList("b","e","c","d");
//1.8前
Collections.sort(a, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
//1.8后
Collections.sort(a, (x,y)->y.compareTo(x));
3,函数式接口,只有函数式接口才支持Lambda 表达式
定义:“函数式接口”是指仅仅只包含一个抽象方法的接口,
@FunctionalInterface注解来定义函数式接口。
4,Date Api更新
LocalDate,LocalTime,LocalDateTime,
now相关的方法可以获取当前日期或时间,
of方法可以创建对应的日期或时间,
with方法可以设置日期或时间信息,
plus或minus方法可以增减日期或时间信息;
DateTimeFormatter用于日期格式化
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
5,Stream
Stream 就如同一个迭代器(Iterator),Stream 可以并行化操作,迭代器只能命令式地、串行化操作。
List<String> list = Arrays.asList("a", "", "c", "g", "abcd","", "j");
long count = list.stream().filter(string->string.isEmpty()).count();
System.out.println("空字符串数量为: " + count);
List<String> filtered = list.stream().
filter(string ->!string.isEmpty()).collect(Collectors.toList());
System.out.println("筛选后的列表: " + filtered);
String merged = list.stream().filter(string ->!string.isEmpty()).
collect(Collectors.joining(", "));
System.out.println("合并字符串: " + merged);
List<Integer> numbers = Arrays.asList(53, 25, 12, 23, 17);
List<Integer> squares = numbers.stream().map( i ->i*i).
distinct().collect(Collectors.toList());
System.out.println("Squares List: " + squares);
IntSummaryStatistics stats = numbers.stream().
mapToInt((x) ->x).summaryStatistics();
System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());