如何使用Java的集合框架如List和Map进行操作?
在Java中,集合框架包括List
(有序的元素列表)和Map
(存储键值对的数据结构)等。
以下是使用List
和Map
的基本操作:
创建集合:
List
:ArrayList
,LinkedList
Map
:HashMap
,TreeMap
,LinkedHashMap
List<String> list = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
添加元素到集合:
List
:add()
,get()
Map
:put()
,remove()
,containsKey()
list.add("Element");
System.out.println(list.get(0)); // Output: Element
map.put("Key", 1);
System.out.println(map.containsKey("Key")); // Output: true
遍历集合:
List
:forEach()
,iterator()
Map
:entrySet()
,keySet()
,values()
list.forEach(System.out::println)); // Print all elements in the list
map.entrySet().forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()))); // Print key-value pairs in the map
以上是基本的使用操作,Java集合框架提供了很多高级功能,如并行处理、观察者模式等。
还没有评论,来说两句吧...