Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách triển khai lambda expression trong JShell Java 9

JShell là REPL đầu tiên của Java, cung cấp môi trường lập trình tương tác command-line. Lambda expression là function không thuộc class nào.

Ví dụ: Tạo Consumer lambda

C:\Users\User> jshell
| Welcome to JShell -- Version 9.0.4
jshell> Consumer<String> s = (String str) -> System.out.println(str)
s ==> $Lambda$14/1268066861@3159c4b8

Gọi lambda

jshell> s.accept("Welcome to Tutorialspoint")
Welcome to Tutorialspoint

Tự động hoàn thành (Tab completion)

Gõ tên biến + dấu chấm + Tab để xem method khả dụng:

jshell> s.
accept(      andThen(     equals(      getClass()   hashCode()   notify()     notifyAll()  toString()   wait(

Ví dụ khác: Function, Predicate

jshell> Function<Integer, Integer> square = x -> x * x
square ==> $Lambda$15/...

jshell> square.apply(5)
$2 ==> 25

jshell> Predicate<String> nonEmpty = s -> !s.isEmpty()
nonEmpty ==> $Lambda$16/...

jshell> nonEmpty.test("hello")
$3 ==> true
jshell> nonEmpty.test("")
$4 ==> false

Lambda với Stream trong JShell

jshell> List.of("a","b","c").stream().map(String::toUpperCase).collect(Collectors.toList())
$5 ==> [A, B, C]

JShell + Lambda = môi trường tuyệt vời để học functional programming, thử Stream API, test logic nhỏ nhanh chóng.