This example shows how to iterate LinkedHashMap in Java using forEach. This example also shows how to iterate LinkedHashMap keys, values and entries using Java 8 forEach.
How to iterate LinkedHashMap using forEach?
If you are using Java version 8 or above, you can use the lambda expression and forEach method from the aggregate operations. You can iterate LinkedhashMap keys, values and entries (mapping of key-value pairs).
How to iterate all keys using forEach?
Use the keySet
method of the LinkedHashMap class and then use the forEach to iterate over all keys.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); lhmap.put(1, "One"); lhmap.put(2, "Two"); lhmap.put(3, "Three"); lhmap.put(4, "Four"); lhmap.put(5, "Five"); /* * Use the keySet method to get the * Set of all keys and then use the * forEach to iterate */ lhmap.keySet().forEach(key -> { System.out.println(key); }); |
Output
1 2 3 4 5 |
1 2 3 4 5 |
How to iterate all values using forEach?
You can use the values
method of the LinkedHashMap class to get all values from the map and then use forEach to iterate over them as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); lhmap.put(1, "One"); lhmap.put(2, "Two"); lhmap.put(3, "Three"); lhmap.put(4, "Four"); lhmap.put(5, "Five"); /* * Use the values method to get the * Collection of all values and then * use the forEach to iterate */ lhmap.values().forEach(value -> { System.out.println(value); }); |
Output
1 2 3 4 5 |
One Two Three Four Five |
How to iterate all entries using forEach?
The above two examples show how to iterate all keys and values of the LinkedHashMap individually. What if you want both keys and values at the same time?
Well, in that case, you can get all the entries (i.e. key-value mappings) from the LinkedHashMap object using the entrySet
method. Once you get the Set of entries, you can use the forEach as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
LinkedHashMap<Integer, String> lhmap = new LinkedHashMap<Integer, String>(); lhmap.put(1, "One"); lhmap.put(2, "Two"); lhmap.put(3, "Three"); lhmap.put(4, "Four"); lhmap.put(5, "Five"); /* * Get all the entries stored in the * LinkedHashMap using the entrySet method * and then use the forEach */ lhmap.entrySet().forEach( entry -> { System.out.println( entry.getKey() + "=>" + entry.getValue() ); }); |
Output
1 2 3 4 5 |
1=>One 2=>Two 3=>Three 4=>Four 5=>Five |
Please also visit how to Iterate LinkedHashMap in various other ways.
This example is a part of the LinkedHashMap in Java Tutorial.
Please let me know your views in the comments section below.
References:
Java 8 LinkedHashMap