1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
/* Get Set view of Keys from Java LinkedHashMap example This Java Example shows how to get a Set of keys contained in LinkedHashMap using keySet method of Java LinkedHashMap class. */ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Set; public class GetSetViewOfKeysFromLinkedHashMapExample { public static void main(String[] args) { //create LinkedHashMap object LinkedHashMap lHashMap = new LinkedHashMap(); //add key value pairs to LinkedHashMap lHashMap.put("1","One"); lHashMap.put("2","Two"); lHashMap.put("3","Three"); /* get Set of keys contained in LinkedHashMap using Set keySet() method of LinkedHashMap class */ Set st = lHashMap.keySet(); System.out.println("Set created from LinkedHashMap Keys contains :"); //iterate through the Set of keys Iterator itr = st.iterator(); while(itr.hasNext()) System.out.println(itr.next()); /* Please note that resultant Set object is backed by the LinkedHashMap. Any key that is removed from Set will also be removed from original LinkedHashMap object. The same is not the case with the element addition. */ //remove 2 from Set st.remove("2"); //check if original LinkedHashMap still contains 2 boolean blnExists = lHashMap.containsKey("2"); System.out.println("Does LinkedHashMap contain 2 ? " + blnExists); } } /* Output would be Set created from LinkedHashMap Keys contains : 1 2 3 Does LinkedHashMap contain 2 ? false */ |
Add Comment