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

JAVA开发工具箱

computeIfAbsent

作用:Map集合提供的一个方法,可以实现 如果 key 不存在则赋值,否则返回现有值

import java.util.HashMap;
import java.util.Map;public class ComputeIfAbsentExample {public static void main(String[] args) {Map<String, Integer> wordCounts = new HashMap<>();// 使用 computeIfAbsent 统计单词出现次数wordCounts.computeIfAbsent("apple", k -> 0); // "apple" 不存在,放入 "apple" -> 0System.out.println(wordCounts); // 输出: {apple=0}wordCounts.computeIfAbsent("banana", k -> 1); // "banana" 不存在,放入 "banana" -> 1System.out.println(wordCounts); // 输出: {banana=1, apple=0}wordCounts.computeIfAbsent("apple", k -> 2); // "apple" 存在,不执行 mappingFunctionSystem.out.println(wordCounts); // 输出: {banana=1, apple=0}  "apple" 的值保持不变// 增加 apple 的计数wordCounts.put("apple", wordCounts.get("apple") + 1);System.out.println(wordCounts); // 输出: {banana=1, apple=1}}
}

场景一:键不存在

import java.util.HashMap;
import java.util.Map;public class ComputeIfAbsentNullExample {public static void main(String[] args) {Map<String, Integer> wordCounts = new HashMap<>();// 键 "grape" 不存在Integer count = wordCounts.computeIfAbsent("grape", k -> null); System.out.println(wordCounts); // 输出: {}  Map 仍然为空System.out.println(count);     // 输出: null  返回值为 null}
}

场景二:键存在,但值为空 

import java.util.HashMap;
import java.util.Map;public class ComputeIfAbsentNullExample2 {public static void main(String[] args) {Map<String, Integer> data = new HashMap<>();data.put("apple", null); // 键存在,但值为 nullInteger value = data.computeIfAbsent("apple", k -> 10);System.out.println(data);   // 输出: {apple=10}  值被更新为 10System.out.println(value); // 输出: 10  返回值为 10}
}

Optional

作用:Optional是java 8提供的,可简化对象和集合的操作

创建 Optional 对象

方法说明
Optional.ofNullable(T value)包装可能为 null 的值:若值为 null,返回 Optional.empty(),否则返回 Optional.of(value)

操作 Optional 对象

方法说明
isPresent()判断是否有值。
ifPresent(Consumer<T> action)如果有值,执行传入的操作(如打印值)。
orElse(T other)如果有值则返回,否则返回默认值 other
orElseGet(Supplier<T> supplier)如果有值则返回,否则通过 Supplier 生成默认值(延迟计算)。
orElseThrow(Supplier<X> exceptionSupplier)如果有值则返回,否则抛出指定异常。

ImmutableMap

 作用:创建不可变的map集合,null不能作为键值对,键不可重复否则报错

ImmutableMap.of("province", "", "city", "", "area", "")

BigDecimal

创建double类型

// 通过静态工厂方法 valueOf 创建(推荐)
BigDecimal bd5 = BigDecimal.valueOf(123.456);

创建Integer类型

BigInteger bi = new BigInteger("123456");

加减乘除

BigDecimal sum = bd1.add(bd2);
BigDecimal difference = bd1.subtract(bd2);
BigDecimal product = bd1.multiply(bd2);
BigDecimal result2 = a.divide(b, 2, RoundingMode.HALF_UP); 

 四舍五入

BigDecimal rounded = bd1.setScale(2, RoundingMode.HALF_UP);
//常用
setScale(1,BigDecimal.ROUND_HALF_UP) 四舍五入(5则向上入),2.35变成2.4

大小比较

BigDecimal a = new BigDecimal("10.5");
BigDecimal b = new BigDecimal("10.5");
BigDecimal c = new BigDecimal("9.8");int result1 = a.compareTo(b); // 结果:0
int result2 = a.compareTo(c); // 结果:1
int result3 = c.compareTo(a); // 结果:-1

转换

//转为int、long、double
BigDecimal a = new BigDecimal("123.456");int intValue = a.intValue(); // 结果:123(直接截断小数)
long longValue = a.longValue(); // 结果:123
double doubleValue = a.doubleValue(); // 结果:123.456//转为string
BigDecimal a = new BigDecimal("123.456");
String str = a.toString(); // 结果:"123.456"

其他

BigDecimal.ZERO 等于 0
BigDecimal.ONE  等于 1

stream操作

//从0开始累加数据
BigDecimal total = accountFlowDtos.stream().filter(flow -> FlowCategory.DISBURSE == flow.getCategory()&& FlowStatus.FAIL != flow.getStatus()).map(AccountFlowDTO::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

Pair

作用:创建只有一个键值对的map集合

<dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version>
</dependency>
import org.apache.commons.lang3.tuple.Pair;public class PairExample {public static void main(String[] args) {// 使用 Pair.of() 创建Pair<String, Integer> pair = Pair.of("Alice", 25);// 获取键和值System.out.println("Key: " + pair.getLeft());  // AliceSystem.out.println("Value: " + pair.getRight());  // 25}
}

 AtomicReference

作用:Java 的 java.util.concurrent.atomic 包中的一个类,它提供了对对象进行原子操作 的能力。它允许我们在多线程环境中安全地操作对象引用

方法描述应用场景
get()获取当前对象引用的值。在多线程环境中安全地读取引用值。
set设置新值,对引用进行更新(不检查当前值)。直接修改引用值,不需要比较当前值。
getAndSet原子地设置新值,并返回旧值。更新值时需要保留旧值进行后续操作。
compareAndSet如果当前值等于 expect,则将其更新为 update,返回 true;否则返回 false实现线程安全的 CAS(Compare-And-Swap)操作。
updateAndGet原子地用自定义函数更新当前值,并返回更新后的值。使用自定义逻辑来原子地更新引用值(如增量操作)。

Converter

在 Spring Framework中,Converter 是一个用于类型转换的接口 

import org.springframework.core.convert.converter.Converter;public class StringToUserConverter implements Converter<String, User> {@Overridepublic User convert(String source) {// 假设 source 格式为 "John,25" (name,age)String[] parts = source.split(",");User user = new User();user.setName(parts[0]);user.setAge(Integer.parseInt(parts[1]));return user;}
}class User {private String name;private int age;// Getters and Setterspublic String getName() { return name; }public void setName(String name) { this.name = name; }public int getAge() { return age; }public void setAge(int age) { this.age = age; }
}

@FunctionalInterface

  1.  必须包含唯一的抽象方法
  2. 可以有默认方法和静态方法
  3. 可以继承其他接口,但不能引入额外的抽象方法
@FunctionalInterface
public interface Calculator {int calculate(int a, int b);// 可以有默认方法default void printResult(int result) {System.out.println("Result: " + result);}// 可以有静态方法static void log(String message) {System.out.println("Log: " + message);}
}

错误示例:多个抽象方法

@FunctionalInterface public interface InvalidInterface { void method1(); void method2(); // 编译报错:函数式接口只能有一个抽象方法 }
@FunctionalInterface
public interface GreetingService {void sayHello(String name);
}public class LambdaExample {public static void main(String[] args) {// 使用 Lambda 表达式实现 GreetingServiceGreetingService greetingService = (name) -> System.out.println("Hello, " + name);greetingService.sayHello("John");}
}
//输出:Hello, John

枚举

方法名描述
name()返回枚举常量的名称,即定义时的字符串。
valueOf(String name)根据枚举常量的名称返回对应的枚举对象,名称必须与定义完全匹配(区分大小写)。
values()返回当前枚举类型的所有枚举常量的数组。
public enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;public static void main(String[] args) {// name(): 返回枚举常量的名称System.out.println("name(): " + Day.MONDAY.name()); // 输出: MONDAY// valueOf(String name): 根据名称返回枚举对象Day day = Day.valueOf("TUESDAY");System.out.println("valueOf(): " + day); // 输出: TUESDAY// values(): 返回所有枚举常量Day[] days = Day.values();System.out.print("values(): ");for (Day d : days) {System.out.print(d.name() + " "); // 输出: MONDAY TUESDAY WEDNESDAY ...}}
}

CompletableFuture

作用:CompletableFuture 是 Java 8 引入的异步编程工具

  • 异步执行:任务在后台线程执行,不阻塞主线程。

  • 组合任务:支持合并多个异步任务的结果。

  • supplyAsync():执行有返回值的异步任务。

  • runAsync():执行无返回值的异步任务。

// 有返回值的异步任务
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {return "Hello";
});// 无返回值的异步任务
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {System.out.println("Task completed.");
});//自定义线程池
ExecutorService customExecutor = Executors.newFixedThreadPool(5);
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {// 耗时操作return "Result";
}, customExecutor);

RestTemplate

作用:用于发送http请求的客户端

创建实例:

private final RestTemplate restTemplate;

POST:

//第一种
User user = new User("John", 30);
User createdUser = restTemplate.postForObject("http://api.example.com/users/{role}", user, User.class, "admin"  // 替换 {role} 为 "admin"
);//第二种
Map<String, String> vars = new HashMap<>();
vars.put("role", "admin");
vars.put("id", "100");User createdUser = restTemplate.postForObject("http://api.example.com/users/{role}/{id}", user, User.class, vars
);//第三种
URI uri = URI.create("http://api.example.com/users");
User createdUser = restTemplate.postForObject(uri, user, User.class);//第四种
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer token");
HttpEntity<User> requestEntity = new HttpEntity<>(user, headers);
User result = restTemplate.postForObject(url, requestEntity, User.class);

GET:

//-------------使用getForObject():直接获取响应体对象--------------------// 使用数组变量
User user = restTemplate.getForObject("http://api.example.com/users/{id}", User.class, 123
);// 使用 Map 变量
Map<String, Object> params = new HashMap<>();
params.put("id", 123);
params.put("type", "admin");User user = restTemplate.getForObject("http://api.example.com/users/{id}/type/{type}", User.class, params
);// 使用完整 URI
URI uri = URI.create("http://api.example.com/users/123");
User user = restTemplate.getForObject(uri, User.class);//------------getForEntity():获取完整响应实体-------------------------
ResponseEntity<User> response = restTemplate.getForEntity("http://api.example.com/users/{id}", User.class, 123
);// 访问响应各部分
HttpStatus statusCode = response.getStatusCode(); // 状态码
HttpHeaders headers = response.getHeaders();      // 响应头
User user = response.getBody();                   // 响应体// 检查状态码
if (statusCode.is2xxSuccessful()) {// 处理成功响应
}

GET和POST通用:

// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer token123");
HttpEntity<Void> requestEntity = new HttpEntity<>(headers);// 发送请求
ResponseEntity<User> response = restTemplate.exchange("http://api.example.com/users/{id}",HttpMethod.GET,requestEntity,User.class,123
);

泛型编程

作用:泛型允许在定义类、接口或方法时使用类型参数,避免在运行时进行强制类型转换,提升代码的类型安全和复用性。

  • T(Type):表示类型。
  • E(Element):表示集合中的元素。
  • K(Key):表示键。
  • V(Value):表示值。
  • N(Number):表示数字。
  • R(Result):表示返回类型。ssssss
public static <T extends WeComResponse> T execute(@NonNull Supplier<T> supplier, @NonNull BiFunction<Integer, String, T> failure) {T response = supplier.get();if (log.isDebugEnabled()) {log.debug("WeCom response: {}", response);}Objects.requireNonNull(response, "WeCom server response invalid");int status = ObjectUtils.ifNull(response.getErrorCode(), 0);return status == 0 ? response : failure.apply(status, response.getErrorMessage());}

 Lists、Sets、Maps

//------------Lists--------------------
// 合并两个列表
List<String> list1 = Arrays.asList("A", "B");
List<String> list2 = Arrays.asList("B", "C");
List<String> union = ListUtils.union(list1, list2); // [A, B, B, C]
// 取两个列表的交集
List<String> intersection = ListUtils.intersection(list1, list2); // [B]
// 取列表的差集(list1 - list2)
List<String> difference = ListUtils.subtract(list1, list2); // [A]
// 将列表按每组3个元素进行分组
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<List<Integer>> partitions = Lists.partition(numbers, 3);//-----------Sets--------------------//交集
Sets.intersection(Sets.newHashSet(1,2,3), Sets.newHashSet(2,3,4));
//并集
Sets.union(Sets.newHashSet(1,2,3), Sets.newHashSet(2,3,4));
//创建指定容量的集合
Sets.newHashSetWithExpectedSize(intersection.size())//----------Maps---------------
同理

Math.random()

作用:生成[0,1)之间的随机数,数据类型为float

//如果需指定生成[min, max]的随机整数
public static int getRandom(int min, int max) {// from-to之间取随机数return (int) (Math.random() * (max- min + 1)) + min;
}//示例
int randomInt = (int)(Math.random() * (20 - 10 + 1)) + 10;
System.out.println(randomInt); // 输出范围:[10, 20]

http://www.xdnf.cn/news/956323.html

相关文章:

  • Easy Excel
  • Shell脚本 - 查看系统信息
  • 设计模式作业
  • Unity中的Time.fixedDeltaTime
  • 9. 线性表的顺序表示和实现(1)
  • TCP和UDP区别
  • 关于 WASM:1. WASM 基础原理
  • linux 下常用变更-8
  • VisualXML全新升级 | 新增数据库编辑功能
  • 怎么让Comfyui导出的图像不包含工作流信息,
  • 三网智能切换技术如何造富?拆解格行WiFi代理的管道收益模型
  • 直播APP平台中如何实现人脸美颜功能?美颜SDK技术详解
  • React第五十七节 Router中RouterProvider使用详解及注意事项
  • Unsafe Fileupload篇补充-木马的详细教程与木马分享(中国蚁剑方式)
  • PLC入门【4】基本指令2(SET RST)
  • 分布式系统简述
  • Appium下载安装配置保姆教程(图文详解)
  • 基于 Three.js 的数字雨波纹效果技术解析
  • 浏览器工作原理11 [#] this:从JavaScript执行上下文视角讲this
  • SpringBoot请求限流(RateLimiter)
  • 针对药品仓库的效期管理问题,如何利用WMS系统“破局”
  • align-items: start和align-items: flex-start的区别
  • 技术创新赋能产业升级:国际数字影像产业园引领变革浪潮
  • 【网络安全】开源系统getshell漏洞挖掘
  • UI 自动化测试工具推荐
  • [KCTF]CORE CrackMe v2.0
  • ​小学五年级的语言来解释符号​
  • ui框架-文件列表展示
  • 拉曼光谱效应:分子指纹的科学与应用
  • 视觉slam--三维刚体运动