JAVA代码优化/使用手册

JAVA代码优化/使用手册

Java8 Stream 集合操作

Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 5);

// 相加
int sum = list.stream().mapToInt(Integer::intValue).sum();
int sum2 = list.stream().reduce(0, Integer::sum);   //从基础值0的基础上累加
int sum3 = list.parallelStream().reduce(0, Integer::sum);   //使用并行流相加
// 获取最大值    //Optional类型可以包装结果为null的值
Optional<Integer> max = list.stream().max(Integer::compareTo);
// 获取最小值
Optional<Integer> min = list.stream().min(Integer::compareTo);
min.ifPresent(System.out::println);

//直接使用Java 8的Stream API对集合进行统计操作
IntSummaryStatistics i = list.stream()
        .mapToInt(Integer::intValue)
        .summaryStatistics();
System.out.println("最大值: " + i.getMax());
System.out.println("最小值: " + i.getMin());
System.out.println("总和: " + i.getSum());
System.out.println("平均值: " + i.getAverage());


// 去重
List<Integer> distinctNumbers = list.stream()
        .distinct()
        .toList();


//利用lambda表达式 使用方法引用 打印输出
list.forEach(System.out::println);
// 遍历所有的键值对 使用Lambda表达式
map.forEach((key, value) -> System.out.println(key + ": " + value));


//筛选和映射
List<String> names = Arrays.asList("aa", "bbb", "ccccc");
List<String> filteredNames = names.stream()     // 遍历输出的结果为 CCCCC
        .filter(name -> name.length() > 4)
        .map(String::toUpperCase)
        .toList();


// 分组和聚合
List<Person> people = Arrays.asList(
        new Person("A", 10),
        new Person("B", 15),
        new Person("C", 20)
);

Map<Integer, List<Person>> personList = people.stream()     //会创建一个新的map
        .collect(Collectors.groupingBy(Person::getAge));

int totalAge = people.stream()  //累加每个人的年龄
        .mapToInt(Person::getAge)
        .sum();


// 分组和聚合
List<Person> peoples = Arrays.asList(
        new Person("A", 10),
        new Person("B", 15),
        new Person("C", 20),
        new Person("D", 25)
);

// 使用Optional和Stream API链式操作处理嵌套对象
Optional<Company> company = getCompany();
String companyName = company.flatMap(Company::getDepartment)
        .flatMap(Department::getManager)
        .map(Manager::getName)
        .orElse("Unknown");

int[] numbers = {1, 2, 3, 4, 5};
// 数组元素求和
int sum = Arrays.stream(numbers).sum();
// 数组排序
int[] sortedNumbers = Arrays.stream(numbers).sorted().toArray(); 

异常类型代码优化

//tyr-with-resource
// 可同时处理多个资源
try (BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("file2.txt"))) {
    // 执行操作
} catch (IOException e) {
    // 处理异常
}

Java 8函数式接口简化回调操作

//不使用lambda表达式
public interface Callback {
    void onSuccess(String result);
    void onFailure(Exception e);
}
 
public void fetchDataAsync(Callback callback) {
    // 异步获取数据
    try {
        String data = fetchData();
        callback.onSuccess(data);
    } catch (Exception e) {
        callback.onFailure(e);
    }
}
 
// 使用匿名内部类调用
fetchDataAsync(new Callback() {
    @Override
    public void onSuccess(String result) {
        System.out.println("Success: " + result);
    }
 
    @Override
    public void onFailure(Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
});
 
 
// 使用lambda表达式后
@FunctionalInterface //Java8引入的一个注解,用于标记该接口为函数式接口
public interface Callback {
    void onSuccess(String result);
    void onFailure(Exception e);
}
 
public void fetchDataAsync(Callback callback) {
    // 异步获取数据
    try {
        String data = fetchData();
        callback.onSuccess(data);
    } catch (Exception e) {
        callback.onFailure(e);
    }
}
 
// 使用Lambda表达式调用
fetchDataAsync(result -> System.out.println("Success: " + result),
               error -> System.err.println("Error: " + error.getMessage()));

字符串操作代码优化

// 类似于c语言的输出语句 阅读时可以知道传入值的类型(和'+'拼接相比)
String name = "LiMing";
int age = 18;
String message = String.format("My name is %s and I'm %d years old.", name, age);

//使用'+'进行拼接:每执行完一条拼接语句会创建一个新的String对象,在产生对象少时推荐使用
//需要多次拼接时:
//    StringBuilder:线程不安全,效率高,不考虑线程安全时使用(如单线程环境),jdk1.5引入
//    StringBuffer:方法都是同步,线程安全,效率比StringBuilder略低,jdk1.0引入
//    StringJoiner:适用于两字符串间要拼接相同的字符串,jdk8引入
//demo
StringBuilder s = new StringBuilder();
s.append("A");s.append(", ");s.append("B");
String result = s.toString();
 
StringBuffer s = new StringBuffer();
s.append("A");s.append(", ");s.append("B");
String result = s.toString();
                                                                                         
StringJoiner s = new StringJoiner(", ");
s.add("A");s.add("B");s.add("C");
String result = s.toString();

//Java 11的字符串方法
// isBlank()和lines()
String text = "Hello\nWorld";
System.out.println(text.isBlank()); // 检查字符串是否为空白
System.out.println(text.lines().count()); // 统计字符串中行的数量

//Java 14的新特性:多行文本块
String html = """
              <html>
                  <body>
                      <h1>Hello, World!</h1>
                  </body>
              </html>
              """;
System.out.println(html);

多线程代码优化

// 使用并发集合简化
// 简化前代码 并发时要保证线程安全 所以使用hashtable  
// 这个代码是给一个key,key存在,它的值进行加一操作
 Hashtable<String, Integer> hashtable = new Hashtable<>();
        
        synchronized (hashtable) {
            if (!hashtable.containsKey("key")) {
                hashtable.put("key", 0);
            } else {
                hashtable.put("key", hashtable.get("key") + 1);
            }
        }
 
//简化后
ConcurrentMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.putIfAbsent("key", 0);
concurrentMap.computeIfPresent("key", (k, v) -> v + 1);

// Java 8的CompletableFuture实现异步编程
//直接使用这个类 目的是为了不用手动创建、启动和管理线程
//实现多个任务并行执行
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> task1());
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> task2());
CompletableFuture<String> combinedFuture = future1.thenCombine(future2, (result1, result2) -> result1 + ", " + result2);
//实现超时处理
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> task());
try {
    String result = future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    // 处理超时情况
}

其它类别代码优化

延迟计算

//能够节省资源,避免重复计算
//如在电商网站推迟商品推荐的计算,直到用户进入推荐页面时才进行
Supplier<String> lazyValue = () -> {
    // 执行一些复杂的计算
    return "Hello World!";
};
 
String value = lazyValue.get(); // 在需要时计算值

对象类型转换

class Student {
    private String name;
    private int age;
    private double score;
 
    // 省略构造方法和其他方法
    // ...
}
class StudentDTO {
    private String name;
    private int age;
 
    // 省略构造方法和其他方法
    // ...
}
 
// 1、可以使用Function类进行类型装换 可适用于复杂场景,比较符合函数式编程代码风格
Function<Student, StudentDTO> studentToDtoConverter = student -> new StudentDTO(student.getName(), student.getAge());
StudentDTO studentDTO = studentToDtoConverter.apply(student);
 
// 2、使用BeanUtils.copyProperties(source, target)方法进行类型转换 使用简单明了
StudentDTO studentDTO = new StudentDTO();
BeanUtils.copyProperties(student, studentDTO)
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值