Registros de casos de optimización de código común

1. Utilice StringBuilder para optimizar el empalme de cadenas:

// 不优化的写法
String result = "";
for (int i = 0; i < 1000; i++) {
    result += i;
}

// 优化的写法
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    resultBuilder.append(i);
}
String result = resultBuilder.toString();

2. Evite calcular repetidamente la longitud de la matriz en un bucle:

// 不优化的写法
for (int i = 0; i < array.length; i++) {
    // 访问数组元素
}

// 优化的写法
int length = array.length;
for (int i = 0; i < length; i++) {
    // 访问数组元素
}

3. Utilice variables locales en lugar de llamar métodos repetidamente: similar a 2

// 不优化的写法
for (int i = 0; i < list.size(); i++) {
    // 多次调用list.get(i)
}

// 优化的写法
int size = list.size();
for (int i = 0; i < size; i++) {
    // 多次使用size
    // 使用list.get(i)
}

4. Elija la clase de colección adecuada:

// 使用ArrayList而不是LinkedList,发明LinkedList都不用LinkedList,可想而知
List<String> arrayList = new ArrayList<>();

// 使用HashSet而不是TreeSet,TreeSet排序消耗性能,但大多数情况下都没必要排序
Set<String> hashSet = new HashSet<>();

5. Utilice el caché de forma adecuada:

// 缓存计算结果
Map<Integer, Integer> cache = new HashMap<>();
int result = cache.computeIfAbsent(input, key -> computeExpensiveOperation(key));

6. Evite la sincronización excesiva:

// 避免过度同步(锁粒度要尽量最小)
private static final Object lock = new Object();

synchronized (lock) {
    // 一些同步操作
}

7. Utilice algoritmos y estructuras de datos adecuados:

// 使用Arrays.sort()进行排序
int[] array = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
Arrays.sort(array);

Arrays.sort()Se utiliza un algoritmo de clasificación eficiente (normalmente una variante basada en Quicksort), que es capaz de clasificar matrices con alto rendimiento en la mayoría de los casos.

8. Reducir la creación de objetos:

// 减少对象创建
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    resultBuilder.append(i);
}
String result = resultBuilder.toString();

9. Utilice un mecanismo a prueba de fallos:

// 使用Iterator并快速失败机制
List<String> list = new ArrayList<>();
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String element = iterator.next();
    // 对element进行操作
}

Si otros subprocesos realizan modificaciones estructurales a la colección (como agregar o eliminar elementos) mientras atraviesan la colección, el mecanismo de falla rápida lanzará inmediatamenteConcurrentModificationException para notificar que la colección ha sido modificado para evitar operaciones continuas en un estado inconsistente.

10. Utilice subprocesos múltiples:

// 使用多线程
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
    // 在线程中执行的代码
});
executor.shutdown();

11. Evite operaciones IO innecesarias:

// 避免不必要的IO操作
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    // 读取文件内容
} catch (IOException e) {
    e.printStackTrace();
}

12. Utilice operaciones bit a bit en lugar de multiplicación y división:

// 使用位运算代替乘法
int result = 5 << 2;  // 相当于 5 * 2^2 = 20

13. Evite el boxeo y unboxing innecesarios:

// 不优化的写法
Integer sum = 0;
for (int i = 0; i < 1000; i++) {
    sum += i;  // 自动装箱和拆箱
}

// 优化的写法
int sum = 0;
for (int i = 0; i < 1000; i++) {
    sum += i;
}

14. Cree objetos utilizando métodos de fábrica estáticos:

// 不优化的写法
Date now = new Date();

// 优化的写法
Date now = Date.from(Instant.now());

15. Uso adecuado de los recursos de prueba:

// 不优化的写法
BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("file.txt"));
    // 读取文件内容
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 优化的写法
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    // 读取文件内容
} catch (IOException e) {
    e.printStackTrace();
}

16. Utilice expresiones Lambda para simplificar el código:

// 不优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
    System.out.println(name);
}

// 优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);

17. Utilice colecciones simultáneas para mejorar el rendimiento de subprocesos múltiples:

// 不优化的写法
List<String> list = new ArrayList<>();
// 在多线程环境下可能会有并发问题

// 优化的写法
List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
// 或者使用并发集合类
List<String> concurrentList = new CopyOnWriteArrayList<>();

18. Utilice Stream API para operaciones de recopilación:

// 不优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> uppercaseNames = new ArrayList<>();
for (String name : names) {
    uppercaseNames.add(name.toUpperCase());
}

// 优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> uppercaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());

19. Utilice variables locales en lugar de acceso a campos:

// 不优化的写法
class MyClass {
    private int myField;

    public int calculate() {
        return myField * 2;
    }
}

// 优化的写法
class MyClass {
    private int myField;

    public int calculate() {
        int localVar = myField;
        return localVar * 2;
    }
}

El uso de variables locales en lugar de acceso directo a los campos tiene como objetivo proporcionar una mejor legibilidad y seguridad al utilizar valores de campo dentro de los métodos.

20. Utilice ConcurrentHashMap en lugar de Map sincronizado:

// 不优化的写法
Map<String, Integer> map = new HashMap<>();
// 在多线程环境下需要额外的同步机制

// 优化的写法
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();

21. Evite crear objetos en bucles:

// 不优化的写法
List<String> myList = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
    myList.add(new String("Element" + i));
}

// 优化的写法
List<String> myList = new ArrayList<>();
String elementPrefix = "Element";
for (int i = 0; i < 1000; i++) {
    myList.add(elementPrefix + i);
}

22. Utilice interfaces en lugar de herencia:

// 不优化的写法
class MyList extends ArrayList<String> {
    // ...
}

// 优化的写法
List<String> myList = new ArrayList<>();

El principio de utilizar interfaces en lugar de herencia se basa en el concepto de diseño de la programación orientada a interfaces. Hay varias razones para respaldar este método de optimización:

  1. Acoplamiento flexible: el uso de interfaces hace que la relación entre clases sea más flexible y reduce el acoplamiento entre clases. Sin utilizar clases de implementación concretas, las interfaces facilitan el reemplazo de implementaciones concretas, lo que hace que el sistema sea más flexible y mantenible.
  2. Polimorfismo: el polimorfismo se puede lograr mediante el uso de interfaces. Es decir, una clase puede existir en múltiples formas y se puede hacer referencia a objetos de diferentes clases usando la misma interfaz, lo que mejora la flexibilidad del código.
  3. Siga el principio de "composición sobre herencia": la herencia a menudo introduce complejidad y dependencias adicionales, mientras que el uso de interfaces es más sencillo. La composición se refiere a la creación de nuevas clases combinando clases e interfaces existentes, en lugar de heredar clases existentes. Esto ayuda a organizar y mantener mejor el código.

23. Utilice expresiones regulares para la manipulación de cadenas:

// 不优化的写法
String result = "Hello, World!".replace("Hello", "Hi");

// 优化的写法
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher("Hello, World!");
String result = matcher.replaceFirst("Hi");

Al utilizar expresiones regulares, puede afrontar mejor algunos requisitos de operación de cadenas más complejos. Sin embargo, para operaciones simples de reemplazo de cadenas, puede ser más conciso y legible usar el método replace directamente.

24. Aseveración de uso legítimo:

// 不优化的写法
if (condition) {
    throw new IllegalStateException("Condition not met");
}

// 优化的写法
assert condition : "Condition not met";

25. Uso razonable de enumeraciones en lugar de constantes:

// 不优化的写法
public static final int STATUS_PENDING = 1;
public static final int STATUS_PROCESSING = 2;
public static final int STATUS_COMPLETED = 3;

// 优化的写法
public enum Status {
    PENDING, PROCESSING, COMPLETED;
}

26. Utilice la agrupación de conexiones:

// 不优化的写法
Connection connection = DriverManager.getConnection(url, username, password);
// 每次都创建新的数据库连接

// 优化的写法
DataSource dataSource = // 初始化数据源(比如 HikariCP)
try (Connection connection = dataSource.getConnection()) {
    // 使用连接
}

27. Utilice flujos paralelos para computación paralela:

// 不优化的写法
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sum = numbers.stream()
                 .mapToInt(Integer::intValue)
                 .sum();

// 优化的写法
int sum = numbers.parallelStream()
                 .mapToInt(Integer::intValue)
                 .sum();

Ventaja:

  1. Paralelismo: utilice flujos paralelos para realizar operaciones en paralelo en múltiples subprocesos, acelerando el procesamiento de grandes conjuntos de datos, especialmente en procesadores multinúcleo modernos.
  2. Simplificación de la computación paralela: los flujos paralelos pueden encapsular la complejidad de la computación paralela en el marco subyacente, eliminando la necesidad de administrar subprocesos manualmente.
  3. Adecuado para determinadas operaciones: los flujos paralelos funcionan mejor en determinados tipos de operaciones (como filtrado, mapeo, agregación de grandes cantidades de datos, etc.).

28. Utilice programación asincrónica para mejorar el rendimiento de la concurrencia:

// 不优化的写法
Future<Integer> future = executorService.submit(() -> {
    // 执行耗时操作
    return result;
});

// 优化的写法
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    // 执行耗时操作
    return result;
}, executorService);

29. Utilice un patrón singleton para reducir la creación de objetos:

// 不优化的写法
class NonSingleton {
    // ...
}

NonSingleton instance = new NonSingleton();

// 优化的写法
class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {
        // 私有构造函数
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

Singleton instance = Singleton.getInstance();

30. Utilice String.contains para comprobar si una cadena contiene una subcadena:

// 不优化的写法
String text = "Hello, World!";
if (text.indexOf("World") != -1) {
    // 处理逻辑
}

// 优化的写法
String text = "Hello, World!";
if (text.contains("World")) {
    // 处理逻辑
}

31. Utilice interfaces y clases abstractas para el diseño de código:

// 不优化的写法
class Dog {
    void bark() {
        // 狗的吠叫逻辑
    }
}

class Cat {
    void meow() {
        // 猫的喵叫逻辑
    }
}

// 优化的写法
interface Animal {
    void makeSound();
}

class Dog implements Animal {
    @Override
    public void makeSound() {
        // 狗的吠叫逻辑
    }
}

class Cat implements Animal {
    @Override
    public void makeSound() {
        // 猫的喵叫逻辑
    }

32. Simplifique las clases anónimas usando expresiones lambda:

// 不优化的写法
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Running");
    }
};

// 优化的写法
Runnable runnable = () -> System.out.println("Running");

33. Evite realizar consultas a la base de datos en bucle:

// 不优化的写法
List<String> ids = // 获取一堆ID
for (String id : ids) {
    User user = userRepository.findById(id);
    // 处理用户对象
}

// 优化的写法
List<String> ids = // 获取一堆ID
List<User> users = userRepository.findAllById(ids);
for (User user : users) {
    // 处理用户对象
}

34. Utilice niveles de registro apropiados:

// 不优化的写法
if (logger.isDebugEnabled()) {
    logger.debug("Some debug information: " + expensiveOperation());
}

// 优化的写法
logger.debug("Some debug information: {}", expensiveOperation());

35. Reducir la duración del método:

Dividir métodos grandes en métodos más pequeños ayuda a mejorar la legibilidad y el mantenimiento del código.

Tomemos como ejemplo el manual de desarrollo de Alibaba, que no estipula claramente el límite superior específico del número de líneas de un método, sino que aboga por organizar el código de acuerdo con el principio de responsabilidad única y el principio de división razonable. Sin embargo, de acuerdo con algunas sugerencias en el "Manual de desarrollo de Java" de Alibaba, se pueden resumir algunos estándares de codificación y mejores prácticas, que también incluyen algunas sugerencias sobre la longitud del método:

  1. Principio de responsabilidad única: un método solo debe hacer una cosa. Si la funcionalidad de un método se vuelve compleja, considere dividirlo en varios métodos más pequeños, cada uno de los cuales es responsable de una subtarea clara.
  2. Comentarios de especificación: Alibaba recomienda utilizar comentarios de especificación antes de los métodos para aclarar la función, los parámetros de entrada, los resultados de salida y otra información del método. Si la funcionalidad de un método requiere demasiados comentarios para explicarse, se puede considerar la división.
  3. Controlar la complejidad: Alibaba recomienda controlar la complejidad de los métodos individuales y tratar de evitar demasiadas estructuras anidadas y códigos largos. Esto también implica que un método no debería ser demasiado largo.

36. Utilice inicialización diferida:

// 不优化的写法
class MyClass {
    private ExpensiveObject expensiveObject = new ExpensiveObject();

    public ExpensiveObject getExpensiveObject() {
        return expensiveObject;
    }
}

// 优化的写法
class MyClass {
    private ExpensiveObject expensiveObject;

    public ExpensiveObject getExpensiveObject() {
        if (expensiveObject == null) {
            expensiveObject = new ExpensiveObject();
        }
        return expensiveObject;
    }
}

37. Utilice IO asincrónica:

// 不优化的写法
InputStream inputStream = new FileInputStream("file.txt");
// 读取文件操作,可能会阻塞线程

// 优化的写法
AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("file.txt"));
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        // 异步读取完成后的处理逻辑
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        // 处理读取失败的逻辑
    }
});

38. Utilice el conjunto de bits (BitSet) para operaciones de bits:

// 不优化的写法
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);

// 优化的写法
BitSet bitSet = new BitSet();
bitSet.set(1);
bitSet.set(2);

39. Utilice List.contains para comprobar si un elemento existe en una colección:

// 不优化的写法
List<String> myList = Arrays.asList("Apple", "Banana", "Orange");
if (myList.indexOf("Banana") != -1) {
    // 处理逻辑
}

// 优化的写法
List<String> myList = Arrays.asList("Apple", "Banana", "Orange");
if (myList.contains("Banana")) {
    // 处理逻辑
}

40. Utilice Files.exists para comprobar si existe un archivo:

// 不优化的写法
File file = new File("lfsun.txt");
if (file.exists()) {
    // 处理逻辑
}

// 优化的写法
Path path = Paths.get("lfsun.txt");
if (Files.exists(path)) {
    // 处理逻辑
}

41. Utilice Math.min y Math.max para obtener los valores mínimo y máximo de dos números:

// 不优化的写法
int a = 5;
int b = 10;
int minValue = (a < b) ? a : b;
int maxValue = (a > b) ? a : b;

// 优化的写法
int a = 5;
int b = 10;
int minValue = Math.min(a, b);
int maxValue = Math.max(a, b);

42. Utilice File.separator para crear rutas de archivos multiplataforma:

// 不优化的写法
String path = "dir\file.txt";

// 优化的写法
String path = "dir" + File.separator + "file.txt";

43. Utilice String.trim para eliminar espacios en ambos extremos de una cadena:

// 不优化的写法
String text = "   Hello, World!   ";
String trimmedText = text.replaceAll("^\s+|\s+$", "");

// 优化的写法
String text = "   Hello, World!   ";
String trimmedText = text.trim();

44. Utilice String.startsWith y String.endsWith para comprobar los prefijos y sufijos de cadenas:

// 不优化的写法
String text = "Hello, World!";
if (text.indexOf("Hello") == 0) {
    // 处理逻辑
}

// 优化的写法
String text = "Hello, World!";
if (text.startsWith("Hello")) {
    // 处理逻辑
}

45. Formato de fecha y hora usando LocalDateTime y DateTimeFormatter:

// 不优化的写法
Date currentDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(currentDate);

// 优化的写法
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);

46. ​​​​Utilice String.substring para interceptar subcadenas:

// 不优化的写法
String text = "Hello, World";
String substring = text.substring(7, 12);

// 优化的写法
String text = "Hello, World";
String substring = text.substring(7);

47. Utilice ThreadLocal para reducir las variables compartidas entre subprocesos:

// 不优化的写法
class SharedResource {
    private int value;
    // ...
}

// 优化的写法
class SharedResource {
    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    // ...
}

48. Utilice parámetros variables para mejorar la flexibilidad del método:

// 不优化的写法
void process(int arg1, int arg2, int arg3) {
    // 处理逻辑
}

// 优化的写法
void process(int... args) {
    // 处理逻辑
}

49. Utilice operadores condicionales (operadores ternarios) para simplificar el código:

// 不优化的写法
int result;
if (condition) {
    result = 1;
} else {
    result = 2;
}

// 优化的写法
int result = condition ? 1 : 2;

50. Utilice clases internas para reducir la visibilidad de clases a nivel de paquete:

// 不优化的写法
package com.lfsun;

class InternalClass {
    // 内部类
}

// 优化的写法
package com.lfsun;

public class OuterClass {
    private class InternalClass {
        // 内部类
    }
}

51. Utilice Arrays.fill para rellenar elementos de matriz:

// 不优化的写法
int[] array = new int[5];
for (int i = 0; i < array.length; i++) {
    array[i] = 42;
}

// 优化的写法
int[] array = new int[5];
Arrays.fill(array, 42);

52. Utilice System.arraycopy para copiar una matriz:

// 不优化的写法
int[] sourceArray = {1, 2, 3, 4, 5};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) {
    targetArray[i] = sourceArray[i];
}

// 优化的写法
int[] sourceArray = {1, 2, 3, 4, 5};
int[] targetArray = new int[sourceArray.length];
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);

Usar System.arraycopy para copiar una matriz es una forma más eficiente. En comparación con el recorrido manual en bucle, tiene las siguientes ventajas:

  1. Optimización del rendimiento: System.arraycopy es un método nativo implementado por el sistema subyacente y suele ser más eficiente que un bucle manual. Esto se debe a que el sistema subyacente se puede optimizar para plataformas y hardware específicos.
  2. Atomicidad: System.arraycopy es una operación atómica, lo que significa que durante todo el proceso de copia de la matriz, no será interrumpida por otros subprocesos, lo que garantiza la coherencia de la copia.
  3. Simplicidad: El uso de System.arraycopy hace que el código sea más conciso y elimina la necesidad de escribir bucles manualmente, lo que mejora la legibilidad y el mantenimiento del código.

53. Utilice List.subList para obtener una sublista:

// 不优化的写法
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
List<String> sublist = new ArrayList<>(list.subList(1, 4));

// 优化的写法
List<String> list = Arrays.asList("A", "B", "C", "D", "E");
List<String> sublist = list.subList(1, 4);

54. Utilice la clase Opcional para evitar excepciones de puntero nulo:

// 不优化的写法
String name = // 获取可能为null的值
if (name != null) {
    System.out.println(name.length());
}

// 优化的写法
Optional<String> optionalName = Optional.ofNullable(name);
optionalName.ifPresent(n -> System.out.println(n.length()));

55. Utilice ConcurrentHashMap para mejorar el rendimiento de concurrencia:

// 不优化的写法
Map<String, Integer> myMap = new HashMap<>();
myMap.put("one", 1);

// 优化的写法
Map<String, Integer> myMap = new ConcurrentHashMap<>();
myMap.put("one", 1);

56. Utilice Opcional.orElseThrow en lugar del manejo de excepciones personalizado:

// 不优化的写法
Optional<String> value = Optional.ofNullable(getValue());
if (value.isPresent()) {
    return value.get();
} else {
    throw new CustomException("Value not found");
}

// 优化的写法
return Optional.ofNullable(getValue())
               .orElseThrow(() -> new CustomException("Value not found"));

57. Utilice referencias de métodos para simplificar el código:

// 不优化的写法
list.forEach(item -> System.out.println(item));

// 优化的写法
list.forEach(System.out::println);

58. Utilice ThreadLocalRandom para obtener números aleatorios:

// 不优化的写法
Random random = new Random();
int randomNumber = random.nextInt(100);

// 优化的写法
int randomNumber = ThreadLocalRandom.current().nextInt(100);

59. Utilice el método contiene de la interfaz Set para verificar los miembros del conjunto:

// 不优化的写法
List<String> list = Arrays.asList("Apple", "Banana", "Orange");
if (list.contains("Banana")) {
    // 处理逻辑
}

// 优化的写法
Set<String> set = new HashSet<>(Arrays.asList("Apple", "Banana", "Orange"));
if (set.contains("Banana")) {
    // 处理逻辑
}

60. Utilice la reflexión y los proxies dinámicos para mejorar la flexibilidad del código:

// 不优化的写法
if (obj instanceof MyClass) {
    ((MyClass) obj).doSomething();
}

// 优化的写法
Method method = obj.getClass().getMethod("doSomething");
method.invoke(obj);

61. Utilice la interfaz del método predeterminado para proporcionar una implementación predeterminada.

// 不优化的写法
interface MyInterface {
    void doSomething();
}

class MyClass implements MyInterface {
    @Override
    public void doSomething() {
        // 具体实现
    }
}

// 优化的写法
interface MyInterface {
    void doSomething();

    default void doSomethingElse() {
        // 默认实现
    }
}

class MyClass implements MyInterface {
    @Override
    public void doSomething() {
        // 具体实现
    }
}

62. Utilice la nueva API de fecha y hora:

// 不优化的写法
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);

// 优化的写法
LocalDate currentDate = LocalDate.now();
int year = currentDate.getYear();

63. Utilice expresiones Lambda para simplificar el manejo de eventos:

// 不优化的写法
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // 处理事件
    }
});

// 优化的写法
button.addActionListener(e -> {
    // 处理事件
});

64. Utilice Files.newBufferedWriter para escribir archivos de texto:


// 不优化的写法
try (PrintWriter writer = new PrintWriter(new FileWriter("file.txt"))) {
    writer.println("Hello, World!");
} catch (IOException e) {
    e.printStackTrace();
}

// 优化的写法
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"))) {
    writer.write("Hello, World!");
} catch (IOException e) {
    e.printStackTrace();
}

65. Utilice métodos de fábrica estáticos en lugar de constructores:


// 不优化的写法
MyObject obj = new MyObject();

// 优化的写法
MyObject obj = MyObject.create();

66. Evite crear clases internas anónimas en bucles:


// 不优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(new Consumer<String>() {
    @Override
    public void accept(String name) {
        // 处理逻辑
    }
});

// 优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> {
    // 处理逻辑
});

67. Utilice la inferencia de tipo de variable local (var):


// 不优化的写法
Map<String, List<String>> myMap = new HashMap<String, List<String>>();

// 优化的写法
var myMap = new HashMap<String, List<String>>();

68. Utilice grupos de subprocesos para mejorar la utilización de subprocesos:

// 不优化的写法
Thread thread = new Thread(() -> {
    // 线程执行的任务
});
thread.start();

// 优化的写法
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
    // 线程执行的任务
});

69. Utilice ClassLoader para cargar clases de forma diferida:

// 不优化的写法
Class<?> myClass = Class.forName("com.lfsun.MyClass");
MyClass instance = (MyClass) myClass.newInstance();

// 优化的写法
Class<?> myClass = ClassLoader.getSystemClassLoader().loadClass("com.lfsun.MyClass");
MyClass instance = (MyClass) myClass.getDeclaredConstructor().new

70. Utilice Stream.distinct para eliminar elementos duplicados:

// 不优化的写法
List<String> myList = Arrays.asList("Apple", "Banana", "Apple", "Orange");
List<String> distinctList = new ArrayList<>(new HashSet<>(myList));

// 优化的写法
List<String> myList = Arrays.asList("Apple", "Banana", "Apple", "Orange");
List<String> distinctList = myList.stream().distinct().collect(Collectors.toList());

71. Utilice String.format en lugar de concatenación de cadenas:

// 不优化的写法
String result = "Hello, " + name + "!";

// 优化的写法
String result = String.format("Hello, %s!", name);

72. Utilice IntStream y DoubleStream en lugar de los bucles tradicionales:

// 不优化的写法
int sum = 0;
for (int i = 1; i <= 100; i++) {
    sum += i;
}

// 优化的写法
int sum = IntStream.rangeClosed(1, 100).sum();

73. Utilice la clase Atomic para mejorar las operaciones atómicas:

// 不优化的写法
int counter = 0;
counter++;

// 优化的写法
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();

74. Utilice StringJoiner para unir cadenas:

// 不优化的写法
String result = "";
for (String s : list) {
    result += s + ", ";
}
result = result.substring(0, result.length() - 2);

// 优化的写法
StringJoiner joiner = new StringJoiner(", ");
for (String s : list) {
    joiner.add(s);
}
String result = joiner.toString();

75. Utilice Arrays.copyOfRange en lugar de copiar matrices manualmente:

// 不优化的写法
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[source.length];
System.arraycopy(source, 0, destination, 0, source.length);

// 优化的写法
int[] source = {1, 2, 3, 4, 5};
int[] destination = Arrays.copyOfRange(source, 0, source.length);

76. Utilice Thread.join para esperar a que finalice el hilo:

// 不优化的写法
Thread thread = new Thread(() -> {
    // 线程执行逻辑
});
thread.start();
// 等待线程结束
try {
    thread.join();
} catch (InterruptedException e) {
    e.printStackTrace();
}

// 优化的写法
Thread thread = new Thread(() -> {
    // 线程执行逻辑
});
thread.start();
// 等待线程结束
thread.join();

77. Utilice Files.lines para leer el contenido del archivo:

// 不优化的写法
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // 处理每行内容
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 优化的写法
try {
    Files.lines(Paths.get("file.txt")).forEach(line -> {
        // 处理每行内容
    });
} catch (IOException e) {
    e.printStackTrace();
}

78. Utilice ReentrantLock para bloqueo explícito:

// 不优化的写法
synchronized (myObject) {
    // 临界区
}

// 优化的写法
ReentrantLock lock = new ReentrantLock();
try {
    lock.lock();
    // 临界区
} finally {
    lock.unlock();
}

79. Utilice el método Map.compute para simplificar las operaciones de Map:


// 不优化的写法
Map<String, Integer> map = new HashMap<>();
String key = "myKey";
if (map.containsKey(key)) {
    map.put(key, map.get(key) + 1);
} else {
    map.put(key, 1);
}

// 优化的写法
map.compute(key, (k, v) -> (v == null) ? 1 : v + 1);

80. Utilice Objects.requireNonNull para comprobar la validez de los parámetros:


// 不优化的写法
public void process(String data) {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null");
    }
    // 处理逻辑
}

// 优化的写法
public void process(String data) {
    Objects.requireNonNull(data, "Data cannot be null");
    // 处理逻辑
}

81. Utilice Files.walk para recorrer el directorio de archivos:


// 不优化的写法
File folder = new File("/folder");
for (File file : folder.listFiles()) {
    // 处理文件
}

// 优化的写法
Path folder = Paths.get("/folder");
try (Stream<Path> paths = Files.walk(folder)) {
    paths.forEach(path -> {
        // 处理文件
    });
} catch (IOException e) {
    e.printStackTrace();
}

82. Utilice el método replaceAll de List para actualizar todos los elementos:

// 不优化的写法
List<String> list = Arrays.asList("apple", "banana", "orange");
for (int i = 0; i < list.size(); i++) {
    list.set(i, list.get(i).toUpperCase());
}

// 优化的写法
List<String> list = Arrays.asList("apple", "banana", "orange");
list.replaceAll(String::toUpperCase);

83. Utilice CopyOnWriteArrayList para mejorar el rendimiento de concurrencia:

// 不优化的写法
List<String> myList = new ArrayList<>();
myList.add("Apple");
myList.add("Banana");
myList.add("Orange");

// 优化的写法
List<String> myList = new CopyOnWriteArrayList<>();
myList.add("Apple");
myList.add("Banana");
myList.add("Orange");

84. Utilice Map.merge para simplificar las operaciones de mapas:


// 不优化的写法
Map<String, Integer> map = new HashMap<>();
String key = "myKey";
if (map.containsKey(key)) {
    map.put(key, map.get(key) + 1);
} else {
    map.put(key, 1);
}

// 优化的写法
map.merge(key, 1, Integer::sum);

85. Utilice expresiones Lambda y recopiladores para operaciones de recopilación:


// 不优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> uppercaseNames = new ArrayList<>();
for (String name : names) {
    uppercaseNames.add(name.toUpperCase());
}

// 优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> uppercaseNames = names.stream()
                                   .map(String::toUpperCase)
                                   .collect(Collectors.toList());

86. Utilice Opcional para resolver comprobaciones nulas anidadas:


// 不优化的写法
if (user != null) {
    Address address = user.getAddress();
    if (address != null) {
        String city = address.getCity();
        if (city != null) {
            // 处理城市信息
        }
    }
}

// 优化的写法
Optional.ofNullable(user)
        .map(User::getAddress)
        .map(Address::getCity)
        .ifPresent(city -> {
            // 处理城市信息
        });

87. Calcule la diferencia horaria usando java.time.Duration e Instant:


// 不优化的写法
long startTime = System.currentTimeMillis();
// 执行一些操作
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;

// 优化的写法
Instant start = Instant.now();
// 执行一些操作
Instant end = Instant.now();
Duration elapsedTime = Duration.between(start, end);

88. Utilice java.nio.file.Path en lugar de la ruta de manipulación de cadenas:


// 不优化的写法
String filePath = "/file.txt";
File file = new File(filePath);

// 优化的写法
Path filePath = Paths.get("/file.txt");

89. Utilice String.isBlank para determinar si una cadena está vacía o contiene solo caracteres en blanco:


// 不优化的写法
if (str != null && !str.trim().isEmpty()) {
    // 处理非空字符串逻辑
}

// 优化的写法
if (str != null && !str.isBlank()) {
    // 处理非空字符串逻辑
}

90. Utilice Map.computeIfAbsent para una inicialización diferida:

// 不优化的写法
Map<String, List<String>> map = new HashMap<>();
if (!map.containsKey("key")) {
    map.put("key", new ArrayList<>());
}
map.get("key").add("value");

// 优化的写法
Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("key", k -> new ArrayList<>()).add("value");

91. Utilice Objects.equals para evitar excepciones de puntero nulo:


// 不优化的写法
boolean isEqual = (obj1 != null) ? obj1.equals(obj2) : (obj2 == null);

// 优化的写法
boolean isEqual = Objects.equals(obj1, obj2);

92. Utilice Math.floorDiv y Math.floorMod en lugar de las operaciones tradicionales de división y módulo:


// 不优化的写法
int quotient = a / b;
int remainder = a % b;

// 优化的写法
int quotient = Math.floorDiv(a, b);
int remainder = Math.floorMod(a, b);

93. Utilice ClassLoader.getSystemResourceAsStream para cargar archivos de recursos en la ruta de clase:


// 不优化的写法
InputStream stream = getClass().getClassLoader().getResourceAsStream("config.properties");

// 优化的写法
InputStream stream = ClassLoader.getSystemResourceAsStream("config.properties");

UsarClassLoader.getSystemResourceAsStream para cargar archivos de recursos en la ruta de clase es un enfoque más recomendado. En comparación congetClass().getClassLoader().getResourceAsStream, tiene las siguientes ventajas:

  1. es más conciso: ClassLoader.getSystemResourceAsStream La llamada de es más concisa y no es necesario obtener el cargador de clases y luego obtener el flujo de recursos.
  2. Evitar NullPointerException: ClassLoader.getSystemResourceAsStream no devuelvenull pero arrojaNullPointerException, lo que ayuda a detectar problemas antes cuando los recursos lo hacen. no existe.
  3. Acceso global a recursos: ClassLoader.getSystemResourceAsStream El uso del cargador de clases del sistema se puede utilizar para acceder a recursos bajo la ruta de clases de la aplicación, no solo a la ruta de clases de la clase actual.

94. Utilice String.repeat para repetir una cadena:

// 不优化的写法
String repeated = "";
for (int i = 0; i < n; i++) {
    repeated += "abc";
}

// 优化的写法
String repeated = "abc".repeat(n);

95. Utilice List.copyOf para crear una colección inmutable:


// 不优化的写法
List<String> originalList = Arrays.asList("a", "b", "c");
List<String> immutableList = Collections.unmodifiableList(new ArrayList<>(originalList));

// 优化的写法
List<String> immutableList = List.copyOf(originalList);

96. Utilice anyMatch y noneMatch de Stream para simplificar la coincidencia de elementos de la colección:


// 不优化的写法
boolean contains = false;
for (String element : list) {
    if (element.equals("target")) {
        contains = true;
        break;
    }
}

// 优化的写法
boolean contains = list.stream().anyMatch(element -> element.equals("target"));

97. Utilice File.toPath para convertir un objeto Archivo en un objeto Ruta:


// 不优化的写法
File file = new File("lfsun.txt");
Path path = file.toPath();

// 优化的写法
Path path = Paths.get("lfsun.txt");

98. Utilice FileSystems.getDefault para obtener el sistema de archivos predeterminado:


// 不优化的写法
Path path = Paths.get("lfsun.txt");

// 优化的写法
Path path = FileSystems.getDefault().getPath("lfsun.txt");

UsarFileSystems.getDefault().getPath para obtener la ruta al sistema de archivos predeterminado es un enfoque más recomendado y tiene las siguientes ventajas sobre Paths.get: a >

  1. Más flexible: FileSystems.getDefault().getPath puede proporcionar más flexibilidad, permitiéndole especificar algunos atributos del sistema de archivos al obtener la ruta. Por ejemplo, puede utilizar diferentes sistemas de archivos, proporcionar propiedades personalizadas del sistema de archivos, etc.
  2. Estilo unificado: utiliza FileSystems.getDefault().getPath para unificar la forma de obtener rutas, haciendo que el código sea más consistente. Esto ayuda a mejorar la legibilidad y el mantenimiento del código.

99. Utilice Collections.newSetFromMap para crear un conjunto basado en mapas:


// 不优化的写法
Map<String, Boolean> map = new ConcurrentHashMap<>();
Set<String> set = map.keySet();

// 优化的写法
Set<String> set = Collections.newSetFromMap(new ConcurrentHashMap<>());

UsarCollections.newSetFromMap para crear basándose en Map es un enfoque más recomendado que usarlo directamente , que tiene las siguientes ventajas: Setmap.keySet()

  1. Seguridad de subprocesos: creado con Collections.newSetFromMap es seguro para subprocesos y la capa inferior usa el < entrante /span>, por lo que es adecuado para entornos multiproceso. SetConcurrentMap
  2. Inmutabilidad: creada mediante Collections.newSetFromMap es inmutable y no se puede pasar< a i=4 >, y otros métodos para modificar su contenido. Esto ayuda a garantizar la coherencia de los datos. Setaddremove
  3. Flexibilidad: se puede lograr pasando diferentes tipos de Map para crear diferentes tipos de Set. Por ejemplo, puede pasar HashMap, TreeMap, etc.

100. Utilice List.sort para ordenar listas:


// 不优化的写法
List<String> list = Arrays.asList("c", "a", "b");
Collections.sort(list);

// 优化的写法
List<String> list = Arrays.asList("c", "a", "b");
list.sort(Comparator.naturalOrder());

Usar List.sort para ordenar listas es un enfoque más recomendado y tiene las siguientes ventajas sobre Collections.sort:

  1. Más directo: el método list.sort() es el método predeterminado de la interfaz List, lo que hace que las operaciones de clasificación sean más directas y consistentes. No es necesario llamar al método de clasificación a través de la clase Collections.
  2. Más flexible: el método list.sort() puede aceptar un parámetro Comparator, lo que hace que la clasificación sea más flexible. Con Comparator, puede implementar reglas de clasificación personalizadas, no solo una clasificación natural.
  3. admite operaciones de transmisión: list.sort() los métodos se pueden usar fácilmente con operaciones de transmisión, como usar Comparator y thenComparing Perform clasificación compleja.

101. Utilice Path.resolve para resolver rutas:


// 不优化的写法
Path path1 = Paths.get("");
Path path2 = Paths.get("file.txt");
Path fullPath = Paths.get(path1.toString(), path2.toString());

// 优化的写法
Path path1 = Paths.get("");
Path path2 = Paths.get("file.txt");
Path fullPath = path1.resolve(path2);

102. Utilice Stream.collect(Collectors.joining) para unir cadenas:

// 不优化的写法
List<String> words = Arrays.asList("Hello", "World", "Java");
String result = words.stream().reduce("", (s1, s2) -> s1 + s2);

// 优化的写法
List<String> words = Arrays.asList("Hello", "World", "Java");
String result = words.stream().collect(Collectors.joining());

103. Utilice Pattern y Matcher para hacer coincidir expresiones regulares:

// 不优化的写法
String text = "The quick brown fox";
boolean containsFox = text.matches(".*fox.*");

// 优化的写法
Pattern pattern = Pattern.compile(".*fox.*");
Matcher matcher = pattern.matcher("The quick brown fox");
boolean containsFox = matcher.matches();

104. Utilice Files.isRegularFile para comprobar si un archivo es un archivo normal:


// 不优化的写法
Path path = Paths.get("file.txt");
if (Files.exists(path) && Files.isRegularFile(path)) {
    // 处理文件逻辑
}

// 优化的写法
Path path = Paths.get("file.txt");
if (Files.isRegularFile(path)) {
    // 处理文件逻辑
}

105. Utilice Opcional para evitar excepciones de puntero nulo:

// 不优化的写法
String result = null;
if (value != null) {
    result = value.toString();
}

// 优化的写法
String result = Optional.ofNullable(value)
                        .map(Object::toString)
                        .orElse(null);

106. Utilice expresiones Lambda para simplificar la creación de comparadores:

// 不优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.sort(new Comparator<String>() {
    @Override
    public int compare(String name1, String name2) {
        return name1.compareTo(name2);
    }
});

// 优化的写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.sort((name1, name2) -> name1.compareTo(name2));

107. Operaciones en cadena usando Opcional.map y Opcional.filter:

// 不优化的写法
Optional<String> result = Optional.ofNullable(getValue());
if (result.isPresent()) {
    String uppercased = result.get().toUpperCase();
    if (uppercased.length() > 5) {
        System.out.println(uppercased);
    }
}

// 优化的写法
Optional.ofNullable(getValue())
        .map(String::toUpperCase)
        .filter(s -> s.length() > 5)
        .ifPresent(System.out::println);

108. Utilice Collectors.joining para unir cadenas:

// 不优化的写法
List<String> list = Arrays.asList("Apple", "Banana", "Orange");
String result = "";
for (String item : list) {
    result += item + ", ";
}
result = result.isEmpty() ? result : result.substring(0, result.length() - 2);

// 优化的写法
List<String> list = Arrays.asList("Apple", "Banana", "Orange");
String result = list.stream().collect(Collectors.joining(", "));

109. Utilice Arrays.asList para crear colecciones inmutables:

// 不优化的写法
List<String> myList = new ArrayList<>();
myList.add("Apple");
myList.add("Banana");
myList.add("Orange");
myList = Collections.unmodifiableList(myList);

// 优化的写法
List<String> myList = Arrays.asList("Apple", "Banana", "Orange");

110. Utilice Comparator.comparing para simplificar la creación de comparadores:

// 不优化的写法
List<Person> people = Arrays.asList(new Person("Alice", 25), new Person("Bob", 30));
people.sort(new Comparator<Person>() {
    @Override
    public int compare(Person person1, Person person2) {
        return Integer.compare(person1.getAge(), person2.getAge());
    }
});

// 优化的写法
List<Person> people = Arrays.asList(new Person("Alice", 25), new Person("Bob", 30));
people.sort(Comparator.comparing(Person::getAge));

111. Utilice StringTokenizer en lugar del método split de String:


// 不优化的写法
String[] tokens = "apple,orange,banana".split(",");

// 优化的写法
StringTokenizer tokenizer = new StringTokenizer("apple,orange,banana", ",");
while (tokenizer.hasMoreTokens()) {
    String token = tokenizer.nextToken();
    // 处理每个token
}

El método de : proporciona más flexibilidad y control y tiene las siguientes ventajas sobre el método es una forma optimizada, especialmente cuando los delimitadores deben ser procesada una por una cadena delimitada por caracteres. StringTokenizer en lugar de usarStringsplitStringTokenizersplit

  1. Procesamiento uno por uno: StringTokenizer permite procesar cadenas separadas por cada delimitador uno por uno. Esto es útil para situaciones en las que se realizan acciones específicas al procesar cada token.
  2. Más opciones de control: StringTokenizer le permite especificar múltiples delimitadores y proporciona más opciones de control, como si devolver delimitadores.
  3. no utiliza expresiones regulares: StringTokenizer no depende de expresiones regulares, por lo que puede ser más rápido que split en algunos casos.

112. Utilice Runtime.getRuntime().availableProcessors() para obtener la cantidad de núcleos de procesador:

int processors = Runtime.getRuntime().availableProcessors();

113. Utilice Arrays.copyOf en lugar de copiar matrices manualmente:


// 不优化的写法
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[source.length];
System.arraycopy(source, 0, destination, 0, source.length);

// 优化的写法
int[] source = {1, 2, 3, 4, 5};
int[] destination = Arrays.copyOf(source, source.length);

114. Utilice LinkedHashMap para mantener el orden de inserción:


// 不优化的写法
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("three", 3);
map.put("two", 2);

// 优化的写法
Map<String, Integer> map = new LinkedHashMap<>();
map.put("one", 1);
map.put("three", 3);
map.put("two", 2);

115. Copia de matriz usando System.arraycopy:


// 不优化的写法
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[source.length];
for (int i = 0; i < source.length; i++) {
    destination[i] = source[i];
}

// 优化的写法
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[source.length];
System.arraycopy(source, 0, destination, 0, source.length);

116. Utilice Files.newInputStream y Files.newOutputStream para operar flujos de archivos:


// 不优化的写法
InputStream inputStream = new FileInputStream("input.txt");
OutputStream outputStream = new FileOutputStream("output.txt");

// 优化的写法
InputStream inputStream = Files.newInputStream(Paths.get("input.txt"));
OutputStream outputStream = Files.newOutputStream(Paths.get("output.txt"));

Manipular flujos de archivos usandoFiles.newInputStream yFiles.newOutputStream es una forma más moderna, flexible y recomendada que la tradicional FileInputStream y FileOutputStream, que tiene las siguientes ventajas:

  1. Procesamiento de rutas más intuitivo: Usar Paths.get("input.txt") para crear rutas es más intuitivo y flexible, y puede manejar rutas relativas y absolutas.
  2. Manejo de excepciones más completo: Files.newInputStream y Files.newOutputStream pueden generar excepciones más completas, lo que facilita la resolución de errores de operación de archivos.
  3. Opciones de configuración más flexibles: Files.newInputStream y Files.newOutputStream admiten algunas opciones de configuración, comoStandardOpenOption, que pueden ser más flexible Cómo abrir el archivo de configuración.

117. Utilice Files.exists para determinar si existe un archivo:


// 不优化的写法
File file = new File("lfsun.txt");
if (file.exists()) {
    // 文件存在逻辑
}

// 优化的写法
if (Files.exists(Paths.get("lfsun.txt"))) {
    // 文件存在逻辑
}

118. Crea archivos usando Files.createFile:


// 不优化的写法
File file = new File("lfsun.txt");
if (!file.exists()) {
    file.createNewFile();
}

// 优化的写法
Files.createFile(Paths.get("lfsun.txt"));

Crear archivos usandoFiles.createFile es una forma más moderna y recomendada, que tiene las siguientes ventajas sobre el método tradicional File:

  1. Procesamiento de rutas más intuitivo: Usar Paths.get("lfsun.txt") para crear rutas es más intuitivo y flexible, y puede manejar rutas relativas y absolutas.
  2. Manejo de excepciones más completo: Files.createFile puede generar excepciones más completas, lo que facilita la resolución de errores de creación de archivos.
  3. Operación atómica: Files.createFile es una operación atómica. Si el archivo ya existe, arrojaráFileAlreadyExistsException para evitar verificar que el archivo existe. condición de carrera entre propiedades y creación de archivos.

119. Utilice Files.delete para eliminar archivos:


// 不优化的写法
File file = new File("lfsun.txt");
if (file.exists()) {
    file.delete();
}

// 优化的写法
Files.deleteIfExists(Paths.get("lfsun.txt"));

120. Utilice Files.walkFileTree para recorrer el árbol de archivos:


// 不优化的写法
FileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        // 处理文件逻辑
        return FileVisitResult.CONTINUE;
    }
};

Files.walkFileTree(Paths.get("/directory"), fileVisitor);

// 优化的写法
Files.walkFileTree(Paths.get("/directory"), new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        // 处理文件逻辑
        return FileVisitResult.CONTINUE;
    }
});

121. Utilice Files.createDirectory para crear un directorio de un solo nivel:


// 不优化的写法
File file = new File("/directory");
if (!file.exists()) {
    file.mkdirs();
}

// 优化的写法
Files.createDirectory(Paths.get("/directory"));

122. Utilice Files.createDirectories para crear directorios de varios niveles:


// 不优化的写法
File file = new File("/multiple/levels");
if (!file.exists()) {
    file.mkdirs();
}

// 优化的写法
Files.createDirectories(Paths.get("/multiple/levels"));

123. Utilice Files.copy para copiar archivos:


// 不优化的写法
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.write(target, Files.readAllBytes(source));

// 优化的写法
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);

124. Utilice Files.isSameFile para comprobar si dos archivos son iguales:


// 不优化的写法
Path file1 = Paths.get("file1.txt");
Path file2 = Paths.get("file2.txt");
if (Files.exists(file1) && Files.exists(file2) && Files.isRegularFile(file1) && Files.isRegularFile(file2)) {
    boolean areSame = Files.isSameFile(file1, file2);
    // 处理相同文件逻辑
}

// 优化的写法
Path file1 = Paths.get("file1.txt");
Path file2 = Paths.get("file2.txt");
if (Files.isRegularFile(file1) && Files.isRegularFile(file2)) {
    boolean areSame = Files.isSameFile(file1, file2);
    // 处理相同文件逻辑
}

125. Utilice Files.getLastModifiedTime para obtener la hora de la última modificación de un archivo:

Path filePath = Paths.get("file.txt");
if (Files.exists(filePath)) {
    long lastModifiedTime = Files.getLastModifiedTime(filePath).toMillis();
    // 处理最后修改时间逻辑
}

126. Utilice Files.size para obtener el tamaño del archivo:


Path filePath = Paths.get("file.txt");
if (Files.exists(filePath)) {
    long fileSize = Files.size(filePath);
    // 处理文件大小逻辑
}

127. Utilice Files.readAttributes para obtener atributos de archivo:

Path filePath = Paths.get("file.txt");
if (Files.exists(filePath)) {
    BasicFileAttributes attributes = Files.readAttributes(filePath, BasicFileAttributes.class);
    FileTime creationTime = attributes.creationTime();
    // 处理文件属性逻辑
}

128. Utilice Files.probeContentType para obtener el tipo de contenido del archivo:

Path filePath = Paths.get("file.txt");
String contentType = Files.probeContentType(filePath);

129. Utilice Files.isSymbolicLink para comprobar si un archivo es un enlace simbólico:


// 不优化的写法
Path filePath = Paths.get("file.txt");
if (Files.exists(filePath) && Files.isSymbolicLink(filePath)) {
    // 处理符号链接逻辑
}

// 优化的写法
Path filePath = Paths.get("file.txt");
if (Files.isSymbolicLink(filePath)) {
    // 处理符号链接逻辑
}

130. Utilice Files.isReadable para comprobar si un archivo es legible:


// 不优化的写法
Path filePath = Paths.get("file.txt");
if (Files.exists(filePath) && Files.isReadable(filePath)) {
    // 处理可读文件逻辑
}

// 优化的写法
Path filePath = Paths.get("file.txt");
if (Files.isReadable(filePath)) {
    // 处理可读文件逻辑
}

131. Utilice Files.isWritable para comprobar si se puede escribir en un archivo:


// 不优化的写法
Path filePath = Paths.get("file.txt");
if (Files.exists(filePath) && Files.isWritable(filePath)) {
    // 处理可写文件逻辑
}

// 优化的写法
Path filePath = Paths.get("file.txt");
if (Files.isWritable(filePath)) {
    // 处理可写文件逻辑
}

132. Utilice Files.getAttribute para obtener atributos de archivo:

Path filePath = Paths.get("file.txt");
if (Files.exists(filePath)) {
    Object attribute = Files.getAttribute(filePath, "basic:creationTime");
    // 处理文件属性逻辑
}

133. Utilice Files.setAttribute para configurar los atributos del archivo:


Path filePath = Paths.get("file.txt");
if (Files.exists(filePath)) {
    Files.setAttribute(filePath, "basic:creationTime", FileTime.from(Instant.now()));
}

134. Utilice Files.isExecutable para comprobar si un archivo es ejecutable:


// 不优化的写法
Path filePath = Paths.get("script.sh");
if (Files.exists(filePath) && Files.isExecutable(filePath)) {
    // 处理可执行文件逻辑
}

// 优化的写法
Path filePath = Paths.get("script.sh");
if (Files.isExecutable(filePath)) {
    // 处理可执行文件逻辑
}

135. Utilice Files.newBufferedReader para leer archivos de texto:

try (BufferedReader reader = Files.newBufferedReader(Paths.get("file.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        // 处理每行内容
    }
} catch (IOException e) {
    e.printStackTrace();
}

136. Utilice DateTimeFormatter en lugar de SimpleDateFormat:


// 不优化的写法
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(new Date());

// 优化的写法
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = LocalDateTime.now().format(formatter);

137. Utilice LocalDate y LocalTime en lugar de Date y Calendar:

// 不优化的写法
Date currentDate = new Date();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);

// 优化的写法
LocalDate currentDate = LocalDate.now();
int year = currentDate.getYear();

138. Utilice el mapa opcional y el mapa plano para operaciones en cadena:

// 不优化的写法
Optional<String> result = Optional.of("Hello");
if (result.isPresent()) {
    String uppercased = result.get().toUpperCase();
    Optional<String> finalResult = Optional.of(uppercased);
}

// 优化的写法
Optional<String> result = Optional.of("Hello");
Optional<String> finalResult = result.map(String::toUpperCase);

Supongo que te gusta

Origin blog.csdn.net/qq_43116031/article/details/134795094
Recomendado
Clasificación