C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Put: We invoke put to add 3 entries to our LinkedHashMap. Then we use entrySet() to loop over them.
ForPrintln: We print the key and value of each Entry to the console with System.out.println.
ConsoleImportant: Notice how the order of our loop is maintained when we access entrySet. The collection never forgot the ordering.
Java program that uses LinkedHashMap
import java.util.LinkedHashMap;
import java.util.Map.Entry;
public class Program {
public static void main(String[] args) {
// Add 3 entries to a LinkedHashMap.
LinkedHashMap<String, Integer> values = new LinkedHashMap<>();
values.put("bird", 10);
values.put("frog", 20);
values.put("snake", 25);
// For LinkedHashMap, we can loop over the items in the order they were added.
// ... A linked list keeps track of the order as we add them.
for (Entry<String, Integer> pair : values.entrySet()) {
System.out.println(pair.getKey() + "/" + pair.getValue());
}
}
}
Output
bird/10
frog/20
snake/25
But: With HashMap (unlike LinkedHashMap) they are looped over in a different order. This program shows the change.
Java program that loops over HashMap
import java.util.HashMap;
import java.util.Map.Entry;
public class Program {
public static void main(String[] args) {
HashMap<String, Integer> values = new HashMap<>();
values.put("bird", 10);
values.put("frog", 20);
values.put("snake", 25);
for (Entry<String, Integer> pair : values.entrySet()) {
System.out.println(pair.getKey() + "/" + pair.getValue());
}
}
}
Output
frog/20
bird/10
snake/25
However: If we do not need the order, HashMap is better because it will be slightly faster in most programs.