随手记录第十二话 -- JDK8-21版本的新增特性记录(Lambda,var,switch,instanceof,record,virtual虚拟线程等)

avatar
作者
筋斗云
阅读量:0

本文主要用于记录jdk8以来的新增特性及使用方法!

1.Java8 Lambda表达式(8)

1.1 方法引用

		List<String> list = List.of("1", "2", "3");         list.forEach(i -> System.out.println(i));         //方法引用         list.forEach(System.out::println); 

1.2 接口支持默认方法

public interface MyTest {          default void defaultMethod(){         System.out.println("default Method");     } } 

1.3 Stream API流式API

		List<String> list = List.of("1", "2", "3");         //过滤再循环         list.stream().filter(i -> !"1".equals(i)).forEach(System.out::println);         //过滤再输出         List<String> list1 = list.stream().filter(i -> !"1".equals(i)).toList();         System.out.println(JSONObject.toJSONString(list1)); //["2","3"]         //过滤再转map         List<Map<String, Object>> list2 = list.stream().filter(i -> !"1".equals(i)).map(s -> {             Map<String, Object> map = new HashMap<>();             map.put("a_" + s, s);             return map;         }).toList();         System.out.println(JSONObject.toJSONString(list2)); //[{"a_2":"2"},{"a_3":"3"}]         //转类型         List<Long> list3 = list.stream().map(Long::valueOf).toList();         System.out.println(JSONObject.toJSONString(list3)); //[1,2,3] 

1.4 Map新增且实用的方法

		Map<String, Integer> map = new HashMap<>();         map.put("a", 1);         map.put("b", 2);         //foreach         map.forEach((key, value) -> System.out.println(key + ": " + value));         //getOrDefault 取值为空返回默认值         int c = map.getOrDefault("c", 22);         System.out.println(c); //22         //replace 如果存在值替换当前key的值         map.replace("b", 10);         System.out.println(map); //{a=1, b=10}         //替换时带匹配值         map.replace("b", 10, 20);         System.out.println(map); //{a=1, b=20}         //replaceAll 可对每个key或者value做操作         map.replaceAll((key, value) -> value + 1);         System.out.println(map); //{a=2, b=21}         //putIfAbsent key不存在才存入         map.putIfAbsent("a", 11);         map.putIfAbsent("c", 3);         System.out.println(map); //{a=2, b=21, c=3}         //computeIfAbsent 如果值不存在 则执行后面的函数         map.computeIfAbsent("d", key -> 4);         System.out.println(map); //{a=2, b=21, c=3, d=4}         //computeIfPresent 如果存在且值非空 可重新计算         map.computeIfPresent("b", (key, value) -> value + 10);         System.out.println(map); //{a=2, b=31, c=3, d=4}         //compute 使用函数计算存入         map.compute("b", (key, value) -> (value == null) ? 40 : value + 1);         map.compute("e", (key, value) -> (value == null) ? 40 : value + 1);         System.out.println(map); //{a=2, b=32, c=3, d=4, e=40}         //merge         map.merge("b", 1, (oldValue, newValue) -> oldValue + newValue);         System.out.println(map); //{a=2, b=33, c=3, d=4, e=40}          //remove 当指定key和值时才删除         map.remove("a", 1);         System.out.println(map); //{a=2, b=33, c=3, d=4, e=40}         map.remove("a", 2);         System.out.println(map); //{b=33, c=3, d=4, e=40}          //of ofEntries 快捷创建 但映射不可变         Map<String, Integer> of = Map.of("a", 1, "b", 2);         System.out.println(of); //{b=2, a=1}         Map<String, Integer> ofEntries = Map.ofEntries(                 Map.entry("a",1),                 Map.entry("b",2)         );         System.out.println(ofEntries); //{b=2, a=1} //        of.put("a",3); //不管新增删除还是修改 俊辉报错 

2. java11 var httpClient相关(11)

		var list = List.of("1", "2", "3");         list.forEach((var e) -> System.out.println(e));          String str = " ";         System.out.println(str.isBlank()); //true         System.out.println(str.isEmpty()); //false  		//java.net.http         JSONObject object = new JSONObject();         object.put("fromId", 11234);         var httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(6)).build();         HttpRequest httpRequest = HttpRequest.newBuilder(URI.create("http://192.168.168.199:9000/xxxxxx"))         //post body请求 //                .setHeader("Content-Type","application/json; charset=utf-8") //                .POST(HttpRequest.BodyPublishers.ofString(object.toJSONString()))                 .build();         HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());         System.out.println(httpResponse.body());           //okhttp3 http请求 //        Request request = new Request.Builder() //                .url(noticeUrl)                 .get() //                .post(RequestBody.create(object.toJSONString(), MediaType.parse("application/json; charset=utf-8"))) //                .build(); //        Response response = Web3jUtils.httpClient.newCall(request).execute(); //        JSONObject jsonObject = JSONObject.parseObject(response.body().string()); //        log.warn("发现提现消息:{},{}", object.toJSONString(), jsonObject.toJSONString()); 

3.新表达式和模块匹配(12-15)

3.1 switch 多行文本 instanceof

		int day = 1;         switch (day){             case 2 -> System.out.println(false);             case 1 -> System.out.println(true);             default -> System.out.println("未知的!");         } 		//多行文本         String str = """                 text                 text                 """;  		//instanceof         if(str instanceof String s1){             System.out.println(s1.toUpperCase(Locale.ROOT));         } 

4.记录 密封类 虚拟线程(16-21)

  • 记录
public record Point(int x, int y) {} 
  • 密封类
public abstract sealed class Shape permits Circle, Square {} public final class Circle extends Shape {} public final class Square extends Shape {} 
  • 虚拟线程
Thread.ofVirtual().start(() -> {     System.out.println("Hello from virtual thread"); });  //使用Executors 创建和管理 ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor(); for (int i = 0; i < 10; i++) {     executor.submit(() -> {         System.out.println("Hello from virtual thread!");     }); } executor.shutdown(); 

以上就是本文的全部内容了!

上一篇:随手记录第十一话 – PHP + yii2 初体验
下一篇:随手记录第十三话 – 关于Python自动化部署神器fabric的应用与差异

非学无以广才,非志无以成学。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!