Search code examples
javalinkedhashmaplinkedhashset

What are the pros and cons of LinkedHashMaps vs. LinkedHashSets?


Could someone explain the main benefits for choosing one over the other and the detriments that come with that choice?


Solution

  • They solve different problems, LinkedHashMap does a mapping of keys to values, a LinkedHashSet simply stores a collection of things with no duplicates.

    A linked hash map is for mapping key/value pairs -- for example, storing names and ages:

    Map<String,Integer> namesAndAges = new LinkedHashMap<String,Integer>();
    namesAndAges.put("Benson", 25);
    namesAndAges.put("Fred", 19);
    

    On the other hand, a linked hash set is for storing a collection of one thing -- names, for example:

    Set<String> names = new LinkedHashSet<String>();
    names.add("Benson");
    names.add("Fred");