一、Map概述
Map是Java中常用的一種數據結構,它把key和value的映射關係組成了一個集合。Map中的key的值是唯一的,不可以重複,value可以重複。Java中提供了多個Map的實現類,如HashMap、TreeMap、LinkedHashMap等。
例如,我們可以使用Map來存儲學生的相關信息,如學生的姓名、學號、成績等。
Map<String, Object> student = new HashMap<>(); student.put("name", "張三"); student.put("id", "20191001"); student.put("score", 95.5);
二、Map循環方式
1.使用Iterator
使用Iterator可以遍歷Map中的每一個元素。
Map<String, Object> student = new HashMap<>(); student.put("name", "張三"); student.put("id", "20191001"); student.put("score", 95.5); Iterator<Map.Entry<String, Object>> it = student.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Object> entry = it.next(); System.out.println(entry.getKey() + ":" + entry.getValue()); }
2.使用for-each循環
使用for-each循環可以更加簡潔地遍歷Map中的每一個元素。
Map<String, Object> student = new HashMap<>(); student.put("name", "張三"); student.put("id", "20191001"); student.put("score", 95.5); for (Map.Entry<String, Object> entry : student.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); }
3.使用Lambda表達式
使用Lambda表達式可以更加簡潔地遍歷Map中的每一個元素。
Map<String, Object> student = new HashMap<>(); student.put("name", "張三"); student.put("id", "20191001"); student.put("score", 95.5); student.forEach((key, value) -> { System.out.println(key + ":" + value); });
三、小結
在Java中,使用Map存儲數據非常方便,我們可以使用多種方式來遍歷Map中的數據。使用Iterator方式可以精確地控制循環的過程,使用for-each循環和Lambda表達式可以讓代碼更加簡潔易懂。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/230651.html