jdk 1.7、jdk 1.8

一,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());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章