The class AbstractMap.SimpleEntry is generic and can be useful.

Answer from Eyal Schneider on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › using pairs in java
Using Pairs in Java | Baeldung
March 13, 2024 - In summary, Pair is best suited for handling a single key-value association or when returning two related values from a method. HashMap, however, is more appropriate for cases that involve storing multiple key-value pairs and require efficient data retrieval and modification capabilities. We can find the Pair class in the javafx.util package.
🌐
W3Schools
w3schools.com › java › java_hashmap.asp
Java HashMap
Java Examples Java Videos Java ... Java Syllabus Java Study Plan Java Interview Q&A ... A HashMap stores items in key/value pairs, where each key maps to a specific value....
Top answer
1 of 2
10

At the simplest level, a key-value pair is just two values, one of which you have designated to be a "key" and the other you have designated to be the "value".

However, it is more common to talk about key-value pairs in the context of a mapping, i.e. a (mathematical) function which maps from a key to the corresponding value or values. Depending on the properties of this mapping, you may constrain the set of key-value pairs. For example, for a 1-to-1 mapping, you need the keys in the set to be unique.


Follow-up questions:

Is this the same as an array?

Well ... an array could be considered as a mapping from a set of indexes (integers) to values. But a mapping is more general. And in Java, arrays have other properties that distinguish them from Maps ... and they have a much simpler, faster, and less memory-hungry implementation.

(Note that in some languages, there is no "array" data type per-se. Instead, the primitive is a "hash" or an "associative array" ... which is a more general map.)

And is a key always a string?

No. A key can be any type. (It is generally a bad idea to use a mutable type as a key, especially if your mapping is implemented using one of the standard Map types in Java. However, even that can work in some circumstances.)

Say a variable of type String points to an object or int variable points to int value. Isn't that variable a "key", and the object a "value"?

No. Or at least, not in a static language like Java. The thing that distinguishes a key-value pair from a variable binding is that the "key" object is data, and hence can take different values. By contrast, a variable's name is hard-wired in the source code of your program: you can't change it at runtime.

(In some dynamic languages, you can create new variables dynamically (at runtime), and for such languages you could argue that variables are key-value pairs in a mapping that represents the scope ... at some point in the program's execution. But Java isn't like that ...)

2 of 2
5

A key-value pair is two values usually connected in such a way that the value is accessed using the key. They are commonly used in various data-structures to provide fast access to values. Check out hashtable data structure for instance (in Java, you can take a look at HashMap or Hashtable)

For example, let's say we have a structure CartoonCharacter holding the mentioned pairs like:

This key-value relationship would look something like:

CartoonCharacter[lastName] = "Bunny";

So if you want to get the value Bunny you would access it through the key lastName.

key = "lastName"
value = CartoonCharacter.get(key)
print (value) // this would print "Bunny"
🌐
CodeGym
codegym.cc › java blog › java objects › pairs in java
Pairs in Java
December 18, 2024 - The Pair in Java is a part of the javafx.util package and is used to represent a pair of values, where one value is associated with a key (key to value relationship). Although it is not a built-in class in the standard Java library, it provides ...
🌐
Delft Stack
delftstack.com › home › howto › java › java key value pair
How to Implement Key Value Pair in Java | Delft Stack
February 12, 2024 - Initially, by importing the java.util package and specifically the Hashtable and Map classes. We declare and instantiate a Hashtable named keyValueTable, with explicit specifications that it will have String keys and Integer values. As we populate our Hashtable with key-value pairs, it’s important to note that Hashtable ensures the uniqueness of keys, and its synchronized nature makes it thread-safe.
🌐
How to do in Java
howtodoinjava.com › home › pairs in java
Java Pair class - key value pair data structure in Java - HowToDoInJava
October 1, 2022 - Learn to work with key value pairs ... class. Read More : Tuples in Java 1. Why we need pairs? A pair provide a convenient way of associating a simple key to value....
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-util-hashmap-in-java-with-examples
HashMap in Java - GeeksforGeeks
HashMap stores data in the form of key-value pairs, where each key is unique.
Published: August 31, 2026
Find elsewhere
🌐
Oracle
docs.oracle.com › en › middleware › webcenter › sites › 12.2.1.4 › java-ref › com › fatwire › rest › beans › KeyValuePair.html
KeyValuePair (Oracle WebCenter Sites Java API Reference)
Java class for keyValuePair complex type. The following schema fragment specifies the expected content contained within this class. <complexType name="keyValuePair"> <complexContent> <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> <sequence> <element name="key" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> <element name="value" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> </sequence> </restriction> </complexContent> </complexType>
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java hashmap › complete guide to java hashmap (with examples)
Complete Guide to Java HashMap (with Examples)
December 5, 2024 - In the key-value pair (also referred to as an entry) to be stored in HashMap, the key must be a unique object whereas values can be duplicated.
🌐
Dev.java
dev.java › learn › using-maps-to-store-key-value-pairs
Using Maps to Store Key Value Pairs
Copyright © 2026 Oracle and/or its affiliates. All rights reserved. Terms of Use | Privacy | Trademarks
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › hashmap-in-java-with-example
HashMap in Java With Examples
September 19, 2022 - HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted as HashMap<Key, Value> or HashMap<K, V>. HashMap in java, is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).
🌐
W3Docs
w3docs.com › java
A KeyValuePair in Java
In Java, a KeyValuePair is a data structure that represents a pair of keys and values, similar to a Map.
🌐
Vultr
docs.vultr.com › java › standard library › java › util › hashmap › put()
Java HashMap put() - Insert Key-Value Pair
September 27, 2024 - The put() method in Java's HashMap class plays a crucial role in adding entries to a hash map, allowing you to store key-value pairs efficiently. This method is fundamental for handling associative arrays in Java, where the keys are unique.
🌐
Reddit
reddit.com › r/learnjava › how does map actually fetch key-value pairs under the hood?
r/learnjava on Reddit: How does Map actually fetch key-value pairs under the hood?
October 29, 2024 -

I came across this behavior by accident while I was learning about Map:

    public static void mapDemo() {
        Map<Long, String> fruitMap = new HashMap<>();

        long id = 123;
        fruitMap.putIfAbsent(id, "apple");
        fruitMap.putIfAbsent(id, "dem apples!");

        System.out.println(fruitMap.get(123)); // Prints "null"
        System.out.println(fruitMap.get((long) 123)); // Prints "apple"

        var num = 123;
    }    

Output:

null
apple

When I try to retrieve the value stored against the key "123" - it depends what the type of the key is along with the value.

If I retrieve it by just using a stray number "123" it retrieves the value `null`
BUT if I type cast this same magic number to "long" type then the stored value "apple" is retrieved.

I understand that for when a stray number of this size gets inferred, it is inferred to "int" type BUT why does it matter? (For example. variable `num` gets inferred to "int" type here)

Please can someone give me an explanation for why does this happen?

Why does the type of key also matter when fetching a value in Map?

Top answer
1 of 3
34
Okay so 123 is an integer. if you type 123L or (long)123 it becomes a long. How ever, if you look at the signature of the get -method in hashmap, it requires an Object as a parameter Therefore each of them is cast into an object: Object a = 123; Object b = (long)123; Now if you try, System.out.println(a.getClass()); System.out.println(b.getClass()); You obviously get class java.lang.Integer class java.lang.Long Okay so why this matters? HashMap is just an array behind the scenes. Each cell of the array is a "bucket", so it contains a list of all the values that are within the the same bucket. So you put something in the map, how does the bucket get assigned? Well, this is not the exact way, but a simplified version. Let's assume the HashMap creates an internal array of size 16. Now, when you "put" something to it, you calculate the hash of the key. For this, there is Object.hashCode(); Which returns effectively just a number. Then: array[key.hashCode() % array.size] = value; So take the hashcode and take modulo of the array length, and you get the index where the value is actually stored. This is why the retrieval is fast: you just take the hashcode and get the index directly, without iterating the whole array. How ever, many objects, while different, have same hashCodes! There are obviously only so many hash codes available, so instead of each cell of array having the value directly, the buckets have a list, in java a LinkedList, where the key-value-pairs are stored. So the addition goes like this: * Calculate the hashCode. * This gives the index * In the list stored at that index, insert the key-value-pair at the end. If many keys have the same hash, the lists become long and that negates some of the advantages of the hashmap itself. So, how is the value retrieved you ask ask the hashmap for the value of specific key the array index is calculated with the hash code from the key iterate the key-value-pair list in that index if the key equals the key that is in the key-value-pair, return the value of that pair. if not, continue iterating And because Integer does not equals Long, you don't find the value. The reason is that equals for most classes check for the class as well, not just the value. Here's the actual code for the get: https://github.com/openjdk/jdk/blob/60364ef0010bde2933c22bf581ff8b3700c4afd6/src/java.base/share/classes/java/util/HashMap.java#L574C1-L592C6 It's a bit dense and the idea is how I explained it. Some differences: Actually not using the "LinkedList" -class, but just a Node that is linked to other Nodes. Sometimes if the list becomes too large, it changes to Trees white are usually possible to iterate faster. EDIT: clarifications and extensions. EDIT2: same thing.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Baeldung
baeldung.com › home › java › java string › split java string into key-value pairs
Split Java String Into Key-Value Pairs | Baeldung
January 8, 2024 - Note that the \b markers ensure that complete key-value pairs are found, making this regex useful for parsing structured data from a given string in the “key=value” format. Then, using the input string, we utilize a Matcher to locate and extract these pairs. We can use Java Sreams to break text into key-value pairs cleanly if we use Java 8 or later.
🌐
Medium
medium.com › @tanishdewase222 › the-java-maps-family-scene-why-do-we-need-key-value-pair-bab823894d78
The Java Map’s Family Scene, Why do we need Key-Value Pair? | by Tanish Dewase | Medium
March 30, 2026 - Map<String, Book> catalog = new HashMap<>(); // ... populate // Get set of keys Set<String> isbns = catalog.keySet(); // Get collection of values Collection<Book> books = catalog.values(); // Get set of entries (most powerful) Set<Map.Entry<String, Book>> entries = catalog.entrySet(); // Example: find all books with title containing "Java" for (Map.Entry<String, Book> entry : entries) { if (entry.getValue().getTitle().contains("Java")) { System.out.println(entry.getKey() + " -> " + entry.getValue().getTitle()); } }
🌐
LabEx
labex.io › tutorials › java-how-to-create-a-map-of-key-value-pairs-in-java-413982
How to create a Map of key-value pairs in Java | LabEx
It is a part of the Java Collections Framework and is widely used in various programming scenarios. A Map is an object that stores a collection of key-value pairs. Each key in the Map must be unique, and it is used to access the corresponding value.