LinkedHashMap是Map接口的哈希表和链表实现。 LinkedHashMap
类不提供排序为TreeMap,但它在插入元素时保持元素的顺序。
在下面的示例中,我们将展示LinkedHashMap
类的各种方法。如下所示:
put()
– 将键和值添加到Map中。get()
– 通过传递键返回值。remove()
– 从Map中删除键和值。size()
– 返回Map的大小。containsKey()
– 如果key存在于map中则返回true,否则返回false。containsValue()
– 如果map中存在value则返回true,否则返回false。clear()
– 从Map中删除所有元素
文件:LinkedHashMapExample.java –
package com.yiibai.tutorial; import java.util.LinkedHashMap; import java.util.Map; /** * @author yiibai * */ public class LinkedHashMapExample { public static void main(String[] args) { Map<String String> map=new LinkedHashMap<>(); /*Adding key and values in LinkedHashMap*/ map.put("1" "One"); map.put("2" "Two"); map.put("3""Three"); map.put("4" "Four"); map.put("5" "Five"); System.out.println("LinkedHashMap key-values:"+map); /*Get value by key from the LinkedHashMap*/ System.out.println("Value of '4' is: "+map.get("4")); /*Removing key and value from the LinkedHashMap */ map.remove("4"); System.out.println("After removal LinkedHashMap Key-Value: " +map); /*Getting size of LinkedHashMap*/ System.out.println("Size of LinkedHashMap is : "+map.size()); /*Checking if key exist in the LinkedHashMap or not*/ System.out.println("Key '3' exist: "+map.containsKey("3")); /*Checking if value exist in the LinkedHashMap or not*/ System.out.println("Key '6' exist: "+map.containsValue("6")); /*Remove all keys and values from the LinkedHashMap*/ map.clear(); System.out.println("After clearing LinkedHashMap: "+map); } }
执行上面代码,得到以下结果:
LinkedHashMap key-values:{1=One 2=Two 3=Three 4=Four 5=Five} Value of '4' is: Four After removal LinkedHashMap Key-Value: {1=One 2=Two 3=Three 5=Five} Size of LinkedHashMap is : 4 Key '3' exist: true Key '6' exist: false After clearing LinkedHashMap: {}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264139.html