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

Cách triển khai Map trong JShell Java 9

JShell (Java 9 REPL) cho phép triển khai các collection: Set, List, Map trực tiếp tại command-line. Map là cặp key-value, key không trùng lặp, mỗi key mapping tối đa 1 value.

Ví dụ: Tạo Map mutable và immutable

C:\Users\User> jshell
| Welcome to JShell -- Version 9.0.4
jshell> Map<String, String> map = new HashMap<>();
map ==> {}
jshell> map.put("raja", "ramesh");
$2 ==> null
jshell> map.put("adithya", "sai");
$3 ==> null
jshell> map.put("jai", "dev");
$4 ==> null
jshell> map.put("chaintaya", "krishna");
$5 ==> null
jshell> map
map ==> {raja=ramesh, jai=dev, chaintaya=krishna, adithya=sai}

jshell> Map<String, String> immutableMap = Collections.unmodifiableMap(map);
immutableMap ==> {raja=ramesh, jai=dev, chaintaya=krishna, adithya=sai}

Các thao tác thường dùng trong JShell

// Tạo Map immutable trực tiếp (Java 9+)
jshell> Map.of("a", "1", "b", "2", "c", "3")
$1 ==> {a=1, b=2, c=3}

// Map.Entry
jshell> Map.entry("key", "value")
$2 ==> key=value

// Map.ofEntries
jshell> Map.ofEntries(Map.entry("x", 10), Map.entry("y", 20))
$3 ==> {x=10, y=20}

// Duyệt Map
jshell> map.forEach((k,v) -> System.out.println(k + "=" + v))
raja=ramesh
jai=dev
chaintaya=krishna
adithya=sai

Lưu ý

  • Map.of(), Map.ofEntries() tạo immutable map – không put/remove được.
  • Cần mutable map → dùng new HashMap<>().
  • JShell tự import java.util.* sẵn.

JShell là môi trường lý tưởng để thử nghiệm Map API mới (Java 9+) như Map.of, computeIfAbsent, merge...