Java程序 打印LinkedHashMap值
LinkedHashMap是Java中的一个预定义类,它类似于HashMap,包含键和它各自的值,与HashMap不同的是,在LinkedHashMap中保留了插入顺序。我们需要打印与键相连的哈希图的值。我们必须遍历LinkedHashMap中的每个键,并通过使用for循环来打印其各自的值。
示例:
输入:
Key- 2 : Value-5
Key- 4 : Value-3
Key- 1 : Value-10
Key- 3 : Value-12
Key- 5 : Value-6
输出: 5, 3, 10, 12, 6
算法:
- 使用For-each循环来迭代LinkedHashMap。
- 使用entrySet()方法,它给出了地图所有映射的集合结构,用于遍历整个地图。对于每个迭代,打印其各自的值
示例:
// Java program to print all the values
// of the LinkedHashMap
import java.util.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
LinkedHashMap<Integer,Integer> LHM = new LinkedHashMap<>();
LHM.put(2,5);
LHM.put(4,3);
LHM.put(1,10);
LHM.put(3,12);
LHM.put(5,6);
// using .entrySet() which gives us the
// list of mappings of the Map
for(Map.Entry<Integer,Integer>it:LHM.entrySet())
System.out.print(it.getValue()+", ");
}
}
输出
5, 3, 10, 12, 6,
时间复杂度: O(n).