Java LinkedHashMap教程

x33g5p2x  于2022-09-25 转载在 Java  
字(6.5k)|赞(0)|评价(0)|浏览(340)

Java LinkedHashMap 是基于 hash tabledoubly linked List 的 Java Map 接口实现。它扩展了 HashMap 类,这是 Map 接口的另一个非常常用的实现

HashMap 类不保证元素的任何特定迭代顺序。它不会跟踪元素的插入顺序,并在每次迭代时以随机顺序生成元素。

如果您想要 Map 中元素的可预测迭代顺序,那么您可以使用 LinkedHashMap。

LinkedHashMap 中的迭代顺序通常是插入元素的顺序。但是,它还提供了一个特殊的构造函数,您可以使用该构造函数将迭代顺序从最近最少访问的元素更改为最近访问的元素,反之亦然。这种迭代顺序在构建 LRU 缓存时很有用。在任何情况下,迭代顺序都是可预测的。

以下是有关 Java 中 LinkedHashMap 的一些重要注意事项 -

  • LinkedHashMap 不能包含重复的键。
  • LinkedHashMap 可以有 null 值和 null 键。
  • 与 HashMap 不同,LinkedHashMap 中元素的迭代顺序是可预测的。
  • 就像 HashMap 一样,LinkedHashMap 不是线程安全的。您必须在多线程环境中显式同步对 LinkedHashMap 的并发访问。

创建和初始化 LinkedHashMap

以下示例展示了如何创建 LinkedHashMap 并向其添加新的键值对。

import java.util.LinkedHashMap;

public class CreateLinkedHashMapExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap
        LinkedHashMap<String, Integer> wordNumberMapping = new LinkedHashMap<>();

        // Adding new key-value pairs to the LinkedHashMap
        wordNumberMapping.put("one", 1);
        wordNumberMapping.put("two", 2);
        wordNumberMapping.put("three", 3);
        wordNumberMapping.put("four", 4);

        // Add a new key-value pair only if the key does not exist in the LinkedHashMap, or is mapped to `null`
        wordNumberMapping.putIfAbsent("five", 5);

        System.out.println(wordNumberMapping);
    }
}
# Output
{one=1, two=2, three=3, four=4, five=5}

访问 LinkedHashMap 的数据

这个例子展示了如何

  • 检查一个键是否存在于 LinkedHashMap 中。
  • 检查 LinkedHashMap 中是否存在值。
  • 修改与 LinkedHashMap 中给定键关联的值。
import java.util.LinkedHashMap;

public class AccessEntriesFromLinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<Integer, String> customerIdNameMapping = new LinkedHashMap<>();

        customerIdNameMapping.put(1001, "Jack");
        customerIdNameMapping.put(1002, "David");
        customerIdNameMapping.put(1003, "Steve");
        customerIdNameMapping.put(1004, "Alice");
        customerIdNameMapping.put(1005, "Marie");

        System.out.println("customerIdNameMapping : " + customerIdNameMapping);

        // Check if a key exists in the LinkedHashMap
        Integer id = 1005;
        if(customerIdNameMapping.containsKey(id)) {
            System.out.println("Found the customer with id " + id + " : " + customerIdNameMapping.get(id));
        } else {
            System.out.println("Customer with id " + id + " does not exist");
        }

        // Check if a value exists in the LinkedHashMap
        String name = "David";
        if(customerIdNameMapping.containsValue(name)) {
            System.out.println("A customer named " + name + " exist in the map");
        } else {
            System.out.println("No customer found with name " + name + " in the map");
        }

        // Change the value associated with an existing key
        id = 1004;
        customerIdNameMapping.put(id, "Bob");
        System.out.println("Changed the name of customer with id " + id + ", New mapping : " + customerIdNameMapping);
    }
}
# Output
customerIdNameMapping : {1001=Jack, 1002=David, 1003=Steve, 1004=Alice, 1005=Marie}
Found the customer with id 1005 : Marie
A customer named David exist in the map
Changed the name of customer with id 1004, New mapping : {1001=Jack, 1002=David, 1003=Steve, 1004=Bob, 1005=Marie}

从 LinkedHashMap 中删除数据

下面的例子展示了如何

  • 从 LinkedHashMap 中删除一个键。
  • 仅当与给定值关联时,才从 LinkedHashMap 中删除键。
import java.util.LinkedHashMap;

public class RemoveEntriesFromLinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, String> husbandWifeMapping = new LinkedHashMap<>();

        husbandWifeMapping.put("Rajeev", "Jennifer");
        husbandWifeMapping.put("John", "Maria");
        husbandWifeMapping.put("Chris", "Lisa");
        husbandWifeMapping.put("Steve", "Susan");

        System.out.println("husbandWifeMapping : " + husbandWifeMapping);

        // Remove a key from the LinkedHashMap
        String wife = husbandWifeMapping.remove("John");
        System.out.println("Removed John and his wife " + wife + " from the mapping. New husbandWifeMapping : " + husbandWifeMapping);

        // Remove a key from the LinkedHashMap only if it is mapped to the given value
        boolean isRemoved = husbandWifeMapping.remove("John", "Susan");
        System.out.println("Did John get removed from the mapping? : " + isRemoved);
    }
}
# Output
husbandWifeMapping : {Rajeev=Jennifer, John=Maria, Chris=Lisa, Steve=Susan}
Removed John and his wife Maria from the mapping. New husbandWifeMapping : {Rajeev=Jennifer, Chris=Lisa, Steve=Susan}
Did John get removed from the mapping? : false

遍历 LinkedHashMap

本节中的示例显示了迭代 LinkedHashMap 的各种方法:

  • 使用 Java 8 forEach 和 lambda 表达式遍历 LinkedHashMap。
  • 使用 Java 8 forEach 和 lambda 表达式遍历 LinkedHashMap 的 entrySet。
  • 使用 iterator() 遍历 LinkedHashMap 的 entrySet。
  • 使用 iterator() 和 Java 8 forEachRemaining() 方法迭代 LinkedHashMap 的 entrySet。
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class IterateOverLinkedHashMapExample {
    public static void main(String[] args) {
        LinkedHashMap<String, String> userCityMapping = new LinkedHashMap<>();

        userCityMapping.put("Rajeev", "Bengaluru");
        userCityMapping.put("Chris", "London");
        userCityMapping.put("David", "Paris");
        userCityMapping.put("Jesse", "California");

        System.out.println("=== Iterating over a LinkedHashMap using Java 8 forEach and lambda ===");
        userCityMapping.forEach((user, city) -> {
            System.out.println(user + " => " + city);
        });

        System.out.println("\n=== Iterating over the LinkedHashMap's entrySet using Java 8 forEach and lambda ===");
        userCityMapping.entrySet().forEach(entry -> {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        });

        System.out.println("\n=== Iterating over the entrySet of a LinkedHashMap using iterator() ===");
        Iterator<Map.Entry<String, String>> userCityMappingIterator = userCityMapping.entrySet().iterator();
        while (userCityMappingIterator.hasNext()) {
            Map.Entry<String, String> entry = userCityMappingIterator.next();
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }

        System.out.println("\n=== Iterating over the entrySet of a LinkedHashMap using iterator() and forEachRemaining ===");
        userCityMappingIterator = userCityMapping.entrySet().iterator();
        userCityMappingIterator.forEachRemaining(entry -> {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        });
    }
}
# Output
=== Iterating over a LinkedHashMap using Java 8 forEach and lambda ===
Rajeev => Bengaluru
Chris => London
David => Paris
Jesse => California

=== Iterating over the LinkedHashMap's entrySet using Java 8 forEach and lambda ===
Rajeev => Bengaluru
Chris => London
David => Paris
Jesse => California

=== Iterating over the entrySet of a LinkedHashMap using iterator() ===
Rajeev => Bengaluru
Chris => London
David => Paris
Jesse => California

=== Iterating over the entrySet of a LinkedHashMap using iterator() and forEachRemaining ===
Rajeev => Bengaluru
Chris => London
David => Paris
Jesse => California

结论

恭喜各位!在本文中,您了解了什么是 LinkedHashMap、如何创建 LinkedHashMap、如何向 LinkedHashMap 添加新的键值对、如何从 LinkedHashMap 中删除条目以及如何迭代 LinkedHashMap。

相关文章

微信公众号

最新文章

更多