[Java11]백기선님의 Java11강의 정리

Reve - 2018/10/18

이 포스트는 백기선님의 동영상 강의를 참고하여 만들었으며, 자세한 내용은 아래 Source 링크를 참고하세요.

이 포스트는 Java11의 새롭게 추가된 기능을 중심으로 작성되었습니다.


# 1. Lambda에서 var 타입 사용하기

JAVA11에서부터 Lambda에서 var타입이 사용 가능하다.

public static void main(String[] args) {
    Flux.just(1, 2, 3, 4)
        .map((var i) -> i * 2)
        .subscribe(System.out::println);
}
1
2
3
4
5

Lambda에서 var타입을 사용하면 TYPE Annotation을 사용할 수 있다.

public static void main(String[] args) {
    Flux.just(1, 2, 3, 4)
        .map((@NonNull var i) -> i * 2)
        .subscribe(System.out::println);
}
1
2
3
4
5
2
4
6
8
1
2
3
4

Source Code (opens new window)


# 2. HttpClient

Java11에서 새로 생긴 HttpClinet는 동기호출 뿐만 아니라 비동기 호출도 사용이 가능하다.

private static void oldStyle() throws IOException {
    URL url = new URL("https://www.naver.com");
    URLConnection connection = url.openConnection();

    try (Scanner scanner = new Scanner(connection.getInputStream())) {
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
    }
}
1
2
3
4
5
6
7
8
9
10
<html>
1
private static void usingHttpClient() throws IOException, InterruptedException {
	HttpClient httpClient = HttpClient.newHttpClient();

	HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create("https://www.naver.com")).build();
	HttpResponse.BodyHandler<String> stringBodyHandler = HttpResponse.BodyHandlers.ofString();

	HttpResponse<String> httpResponse = httpClient.send(httpRequest, stringBodyHandler);

	System.out.println(httpResponse.body());
}
1
2
3
4
5
6
7
8
9
10
<html>
1
private static void usingHttpClient_usingAsync() throws IOException, InterruptedException {
	HttpClient httpClient = HttpClient.newHttpClient();

	HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create("https://www.naver.com")).build();
	HttpResponse.BodyHandler<String> stringBodyHandler = HttpResponse.BodyHandlers.ofString();

	CompletableFuture<HttpResponse<String>> future = httpClient.sendAsync(httpRequest, stringBodyHandler);

	future.thenApply(HttpResponse::body)
	    .thenAccept(System.out::println);

	System.out.println("print first");
	Thread.sleep(1000);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
print first
<html>
1
2

# 3. String의 새로 추가된 함수

함수명 설명
trim() 앞뒤로 공백을 제거
strip() [NEW] 유니코드 공백문자(ex:\u205f)를 포함하여 앞 뒤 공백을 제거
stripLeading() [NEW] 유니코드 공백문자(ex:\u205f)를 포함하여 앞 공백을 제거
stripTrailing() [NEW] 유니코드 공백문자(ex:\u205f)를 포함하여 뒤 공백을 제거
isEmpty() 문자열의 길이가 0이면 true
isBlank() [NEW] 문자열의 길이가 0이거나 모두 공백문자이면 true
lines() [NEW] 개행문자(\n)를 기준으로 문자열을 잘라 Stream<String>으로 반환
repeat(int count) [NEW] 문자열을 count만큼 반복한 문자열을 반환
private static void trim() {
	String str = " reve ";
	String trim = str.trim();

	System.out.println(String.format("trim : [%s] > [%s]", str, trim));
}
1
2
3
4
5
6
trim : [ reve ] > [reve]
1
private static void strip() {
	String str = "\u205f reve \u205f";

	String strip = str.strip();
	System.out.println(String.format("strip : [%s] > [%s]", str, strip));

	String stripLeading = str.stripLeading();
	System.out.println(String.format("stripLeading : [%s] > [%s]", str, stripLeading));

	String stripTrailing = str.stripTrailing();
	System.out.println(String.format("stripTrailing : [%s] > [%s]", str, stripTrailing));
}
1
2
3
4
5
6
7
8
9
10
11
12
strip : [ reve ] > [reve]
stripLeading : [ reve ] > [reve ]
stripTrailing : [ reve ] > [ reve]
1
2
3
private static void isEmpty() {
	String str = "";
	System.out.println(String.format("isEmpty [%s] ? %b", str, str.isEmpty()));

	str = " ";
	System.out.println(String.format("isEmpty [%s] ? %b", str, str.isEmpty()));

	str = "\t";
	System.out.println(String.format("isEmpty [%s] ? %b", str, str.isEmpty()));
}
1
2
3
4
5
6
7
8
9
10
isEmpty [] ? true
isEmpty [ ] ? false
isEmpty [	] ? false
1
2
3
private static void isBlank() {
	String str = "";
	System.out.println(String.format("isBlank [%s] ? %b", str, str.isBlank()));

	str = " ";
	System.out.println(String.format("isBlank [%s] ? %b", str, str.isBlank()));

	str = "\t";
	System.out.println(String.format("isBlank [%s] ? %b", str, str.isBlank()));
}
1
2
3
4
5
6
7
8
9
10
isBlank [] ? true
isBlank [ ] ? true
isBlank [	] ? true
1
2
3
private static void lines() {
	String str = "aaa\nbbb\nccc";
	System.out.println("lines : ");
	str.lines().forEach(System.out::println);
}
1
2
3
4
5
lines : 
aaa
bbb
ccc
1
2
3
4
private static void repeat() {
	String str = "testMessage ";
	System.out.println(String.format("%srepeat 5 : %s", str, str.repeat(5)));
}
1
2
3
4
testMessage repeat 5 : testMessage testMessage testMessage testMessage testMessage 
1

Source Code (opens new window)


# 4. Collection의 새로운 함수

Collection에서 Array로 변경하기 위한 toArray()함수 추가

public static void main(String[] args) {
	List<String> stringList = List.of("testa", "testb", "testc");
	Object[] objects = stringList.toArray();
	System.out.println(Arrays.toString(objects));

	String[] strings1 = stringList.toArray(new String[0]);
	System.out.println(Arrays.toString(strings1));

	String[] strings2 = stringList.toArray(String[]::new);
	System.out.println(Arrays.toString(strings2));
}
1
2
3
4
5
6
7
8
9
10
11
[testa, testb, testc]
[testa, testb, testc]
[testa, testb, testc] 
1
2
3

Source Code (opens new window)


# 5. 파일을 쉽고 빠르게 쓰고 읽기 위한 Files의 새로운 함수

함수명 설명
readString() [NEW] 파일에 들어있는 문자열을 읽어 String으로 반환
writeString() [NEW] 문자열을 파일로 작성
public static void main(String[] args) throws IOException {
	Resource resource = new ClassPathResource("/testfile");
	Path testfilePath = Path.of(resource.getURI());
	String str = Files.readString(testfilePath);

	System.out.println("READ ========================");
	System.out.println(str);

	Path tempFilePath = Files.createTempFile("temp", ".txt");
	Files.writeString(tempFilePath, str);

	System.out.println("WRITE ========================");
	System.out.println(Files.readString(tempFilePath));
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
READ ========================
file
test
temp
file
WRITE ========================
file
test
temp
file
1
2
3
4
5
6
7
8
9
10

Source Code (opens new window)

Java 카테고리 내 다른 포스트