当前位置: 首页 > news >正文

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

本文主要用于记录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"]//过滤再转mapList<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);//foreachmap.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}//mergemap.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()); //trueSystem.out.println(str.isEmpty()); //false//java.net.httpJSONObject 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 = """texttext""";//instanceofif(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 初体验
下一篇:随手记录第十三话 – xxx

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

http://www.lryc.cn/news/411768.html

相关文章:

  • SpringCloud网关 SpringBoot服务 HTTP/HTTPS路由/监听双支持
  • JavaScript做网页是否过期的处理
  • python coding时遇到的问题
  • 攻防演练号角吹响,聚铭铭察高级威胁检测系统助您零失分打赢重保攻坚战
  • 个人量化交易兴起!有什么好用的量化软件推荐?迅投QMT量化平台简介!
  • SQL labs-SQL注入(七,sqlmap对于post传参方式的注入,2)
  • SAM 2: Segment Anything in Images and Videos
  • 软件测试面试,如何自我介绍?
  • 力扣第四十七题——全排列II
  • Springer旗下中科院2区TOP,国人优势大!
  • 【C++】C++入门知识详解(下)
  • 分压电阻方式的ADC电压校准
  • 使用Postman测试API短轮询机制:深入指南
  • 明清进士人数数据
  • C# 串口通信(通过serialPort控件发送及接收数据)
  • 数据安全的新盾牌:SQL Server数据库镜像技术详解
  • 【C语言版】数据结构教程(一)绪论(上)
  • 酒后为什么总感觉渴?
  • Docker安装OwnCloud私有云盘对接ceph
  • 创建了Vue项目,需要导入什么插件以及怎么导入
  • abstract 关键字
  • 用Python编写你的网络监控系统详解
  • 操作系统——虚拟内存
  • Zoom视频会议软件使用
  • MVC软件设计模式及QT的MVC架构
  • 使用WSL通过SSH连接并运行图形界面程序
  • 柳湛宇-简历
  • 6-1 从全连接层到卷积
  • 【Android Studio】项目目录结构
  • electron-builder打包vue2项目问题合集