在Java中,Map是一種非常有用的數據結構,它允許我們存儲鍵值對。在不同的場景下,Map可以有多種應用。以下是一些常見的應用場景:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 4, 5, 6, 6);
Set<Integer> set = new HashSet<>(list);
Map<Integer, Integer> map = new HashMap<>();
for (Integer num : set) {
map.put(num, null);
}
set = new HashSet<>(map.keySet());
Map<String, String> map = new HashMap<>();
map.put("name", "John");
map.put("age", "30");
String name = map.get("name"); // 查找name對應的值
Map<String, Integer> map = new HashMap<>();
map.put("apple", 5);
map.put("banana", 8);
map.put("orange", 3);
int appleCount = map.get("apple"); // 統計apple出現的次數
Map<Integer, String> cache = new HashMap<>();
cache.put(1, calculateResult(1)); // 計算并緩存結果
String result = cache.get(2); // 從緩存中獲取結果,避免重新計算
List<Employee> employees = Arrays.asList(
new Employee("John", "Sales"),
new Employee("Jane", "Marketing"),
new Employee("Mike", "Sales"),
new Employee("Lucy", "Marketing")
);
Map<String, List<Employee>> groups = new HashMap<>();
for (Employee employee : employees) {
String department = employee.getDepartment();
if (!groups.containsKey(department)) {
groups.put(department, new ArrayList<>());
}
groups.get(department).add(employee);
}
這些只是Map在不同場景下的一些應用,實際上Map在Java編程中有非常廣泛的應用。