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 ) ;
int sum3 = list. parallelStream ( ) . reduce ( 0 , Integer :: sum ) ;
Optional < Integer > max = list. stream ( ) . max ( Integer :: compareTo ) ;
Optional < Integer > min = list. stream ( ) . min ( Integer :: compareTo ) ;
min. ifPresent ( System . out:: println ) ;
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 ( ) ;
list. forEach ( System . out:: println ) ;
map. forEach ( ( key, value) -> System . out. println ( key + ": " + value) ) ;
List < String > names = Arrays . asList ( "aa" , "bbb" , "ccccc" ) ;
List < String > filteredNames = names. stream ( )
. 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 ( )
. 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 < 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 ( ) ;
异常类型代码优化
try ( BufferedReader br = new BufferedReader ( new FileReader ( "file1.txt" ) ) ;
BufferedWriter bw = new BufferedWriter ( new FileWriter ( "file2.txt" ) ) ) {
} catch ( IOException e) {
}
Java 8函数式接口简化回调操作
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 ( ) ) ;
}
} ) ;
@FunctionalInterface
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 ( result -> System . out. println ( "Success: " + result) ,
error -> System . err. println ( "Error: " + error. getMessage ( ) ) ) ;
字符串操作代码优化
String name = "LiMing" ;
int age = 18 ;
String message = String . format ( "My name is %s and I'm %d years old." , name, age) ;
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 ( ) ;
String text = "Hello\nWorld" ;
System . out. println ( text. isBlank ( ) ) ;
System . out. println ( text. lines ( ) . count ( ) ) ;
String html = """
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
""" ;
System . out. println ( html) ;
多线程代码优化
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 ) ;
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;
}
Function < Student , StudentDTO > studentToDtoConverter = student -> new StudentDTO ( student. getName ( ) , student. getAge ( ) ) ;
StudentDTO studentDTO = studentToDtoConverter. apply ( student) ;
StudentDTO studentDTO = new StudentDTO ( ) ;
BeanUtils . copyProperties ( student, studentDTO)