Lambda表达式
/** * Lambda表达式 */ private static void lambda(){ // JDK8 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); list.forEach(n -> System.out.println(n)); // JDK17 List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5); //用到var....... list2.forEach((var n) -> System.out.println(n)); }
Pattern Matching for instanceof
/** * Pattern Matching for instanceof */ private static void pattern(Object obj){ // JDK8 if (obj instanceof String) { String str = (String) obj; System.out.println(str.toUpperCase()); } else { System.out.println(obj); } // JDK17 if (obj instanceof String str) { System.out.println(str.toUpperCase()); } else { System.out.println(obj); } }
新的集合操作API
/** * 新的集合操作API * JDK8引入了Stream API,使得对集合的操作更加简洁和方便。JDK17在此基础上又增加了一些新的API, * 比如toList()和toSet()等,使得将Stream转换为List或Set变得更加简单。 */ private static void api(){ // JDK8 List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); int sum = list.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).sum(); // JDK17 List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> evenList = list2.stream().filter(n -> n % 2 == 0).toList(); Set<Integer> oddSet = list2.stream().filter(n -> n % 2 != 0).collect(Collectors.toSet()); }
改进的Switch语句
/** * 改进的Switch语句 * JDK17引入了新的Switch语句,支持使用表达式作为条件,同时也支持使用Lambda表达式作为分支语句。 */ private static void newSwitch(String dayOfWeek){ // JDK8 switch (dayOfWeek) { case "MON": case "TUE": case "WED": case "THU": case "FRI": System.out.println("Weekday"); break; case "SAT": case "SUN": System.out.println("Weekend"); break; default: System.out.println("Invalid day"); } // JDK17 String dayType = switch (dayOfWeek) { case "MON", "TUE", "WED", "THU", "FRI" -> "Weekday"; case "SAT", "SUN" -> "Weekend"; default -> { System.out.println("Invalid day"); yield "Invalid day"; } }; }
新的HTTP Client API
/** * 新的HTTP Client API * JDK11引入了新的HTTP Client API,使得对HTTP请求的处理变得更加简单和方便。 */ private static void client() throws Exception{ // JDK8 // 使用第三方HTTP库 // JDK17 HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://www.example.com/")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); }
标签:case,jdk17,System,JDK17,jdk8,println,对比,API,out From: https://www.cnblogs.com/nxjblog/p/18163241