Java Generate All Key Values Of A Map
The java.util.HashMap.keySet method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys or we can create a new set and store the key elements in them.
- What this is. This file is included in the DevDaily.com 'Java Source Code Warehouse' project.The intent of this project is to help you 'Learn Java by Example' TM.Other links. The search page; Other source code files at this package level.
- Map with different types for values. Ask Question. A map (that can work as a cache) that has strings as keys and values of different types. In my real case once set the key/values in the map will not change. Compare this to the typesafe heterogeneous container as defined in Effective Java. There the type is part of the key (actually.
- Inserting Elements Into a Java Map
- Get Elements From a Java Map
- Iterating the Keys of a Java Map
- Iterating the Values of a Java Map
- Iterating the Entries of a Java Map
- Functional Operations in Java Map
The Java Map interface, java.util.Map
, represents a mapping between a key and a value. More specifically, a JavaMap can store pairs of keys and values. Each key is linked to a specific value. Once stored in a Map
, you can later look up the value using just the key.
The Java Map
interface is not a subtype of the Collection
interface. Therefore it behaves a bit different from the rest of the collection types.
Java Map Tutorial Video
If you prefer video, I have a video version of this Java Map tutorial available here: Java Map Tutorial
Java Map Implementations
Since Map
is an interface you need to instantiate a concrete implementation of the Map
interface in order to use it. The Java Collections API contains the following Map
implementations:
- java.util.HashMap
- java.util.Hashtable
- java.util.EnumMap
- java.util.IdentityHashMap
- java.util.LinkedHashMap
- java.util.Properties
- java.util.TreeMap
- java.util.WeakHashMap
In my experience, the most commonly used Map
implementations are HashMap
and TreeMap
.
Each of these Map
implementations behaves a little differently with respect to the order of the elements when iterating the Map
, and the time (big O notation) it takes to insert and access elements in the maps.
HashMap
maps a key and a value. It does not guarantee any order of the elements stored internally in the map.
TreeMap
also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated - which is the sort order of the keys or values. Check out the Java Map
JavaDoc for more details.
Nfs rivals key generator no survey download. Feb 10, 2017 need for speed rivals origin key free. Need for speed rivals key. Need for speed rivals product key download. Nfs rivals key generator no survey. Need for speed rivals pc activation code. Nfs rivals serial keyDownload. Need for speed rivals serial key generator v1.03 hacksbook. Need for speed rivals cd key generator v1.0.exe archives i need.
The HashMap implementation is typically the fastest of the two Map implementations, so whenever you don't need to sort the elements in the Map you can just use a HashMap. Otherwise use a TreeMap.
Create a Map
To create a Java Map you must create an instance of one the classes that implement the Java Map interface. Here are a few examples of how to create a Map
instance:
Generic Java Map
By default you can put any Object
into a Map
, but from Java 5, Java Generics makes it possible to limit the types of object you can use for both keys and values in a Map
. Here is an example:
This Map
can now only accept String
objects for keys, and MyObject
instances for values. You can then access and iterate keys and values without casting them. Here is how it looks:
If you know the type of the objects being stored in the Map it is considered good practice to always specify a generic type when declaring and creating a Java Map. The generic type helps you avoid inserting the wrong objects, and makes it easier for people reading your code to understand what kind of objects the Map contains. Throughout the rest of this tutorial I will be using generic types on all Map examples whenever it makes sense.
For more information about Java Generics, see the Java Generics Tutorial.
Inserting Elements Into a Java Map
To add elements to a Map
you call its put()
method. Here are a few examples:
The three put()
calls maps a string value to a string key. You can then obtain the value using that key, as we will see in the next section.
Only Objects Can Be Inserted
Only Java objects can be used as keys and values in a Java Map. In case you pass primitive values (e.g. int, double etc.) to a Map
as key or value, the primitive values will be auto-boxed before being passed as parameters. Here is an example of auto-boxing primitive parameters passed to the put()
method:
The value passed to the put()
method in the above example is a primitive int
. Java auto-boxes it inside an Integer
instance though, because the put()
method requires an Oject
instance as both key and value. Auto-boxing would also happen if you passed a primitive as key to the put()
method.
Subsequent Inserts With Same Key
A given key can only occur in a Java Map
one time. That means, that only a single key + value pair for each key can exist in the Map
at the same time. In other words, for the key 'key1' only one value can be stored in the same Map
instance. Of course you can store values for the same key in different Map
instances.
If you call put()
more than once with the same key, the latest value passed to put()
for that key will overwrite what is already stored in the Map
for that key. In other words, the latest value replaces the existing value for the given key.
Null Keys
Quite surprisingly you can use the value null
as a key in a Java Map. Here is an example of using a null
key in a Java Map:
To obtain the value stored by the null
key you call the get()
method with null
as parameter value. Here is an example of getting the value for the null
key of a Java Map:
Null Values
The value of a key + value pair stored in a Map
is allowed to be null - so this is valid:
Just keep in mind that you will get a null out when you call get()
later with that key - so this will return null:
The value
variable will have the value null
after this code has been executed, if a null
value was inserted for this key earlier (like in the previous example).
Inserting All Elements From Another Map
The Java Map
interface has a method called putAll()
which can copy all key + value pairs (entries) from another Map
instance into itself. In set theory, this is also referred to as the union of the two Map
instances.
Here is an example of copying all entries from one Java Map
into another via putAll()
:
After running this code the Map
referenced by variable mapB
will contain both of the key + value entries inserted into mapA
at the beginning of the code example.
The copying of entries only goes one way. Calling mapB.putAll(mapA)
will only copy entries from mapA
into mapB
, not from mapB
into mapA
. To copy entries the other way, you would have to execute the code mapA.putAll(mapB)
.
Get Elements From a Java Map
To get a specific element stored in a Java Map
you call its get()
method, passing along the key for that element as parameter. Here is an example of getting a value stored in a Java Map
:
Notice that the get()
method returns a Java Object
, so we have to cast it to a String
(because we know the value is a String). Later in this Java Map tutorial you will see how to use Java Generics to type the Map
so it knows what specific key and value types it contains. This makes type casting unnecessary, and makes it harder to insert the wrong values into the Map
by accident.
If we had specified a generic type for the key and value of the Map, then it would not have been necessary to cast the object returned by get()
method. Here is how that would look:
Get or Default Value
The Java Map
interface has a getOrDefault()
method which can return a default value supplied by you - in case no value is stored in the Map
by the given key. Here is an example of getting a value from a Java Map
with a backup default value:
This example creates a Map
and stores three values in it using the keys A
, B
and C
. Then the example calls the Map
getOrDefault()
method, passing the String E
as key, along with a default value - the String default value
. Since the Map
does not contain any object stored by the key E
the given default value will be returned - which is the String default value
passed as the last parameter to the getOrDefault()
method.
Checking if Map Contains Key
You can check if a Java Map
contains a specific key using the containsKey()
method. Here is how that looks:
After running this code, the hasKey
variable will have the value true
if a key + value pair was inserted earlier with the String key 123
, and false if no such key + value pair was inserted.
Checking if Map Contains Value
The Java Map
interface also has a method that enables you to check if the Map
contains a certain value. The method is called containsValue()
. Here is how calling the containsValue()
looks:
After executing this code the hasValue
variable will contain the value true
if a key + value pair was inserted ealier with the String value 'value 1'
, and false if not.
Iterating the Keys of a Java Map
There are several ways to iterate the keys stored in a Java Map
. The most used methods for iterating the keys are:
- Via the key
Iterator
- Via the for-each loop
- Via a
Stream
All methods will be covered in the following sections.
Using a Key Iterator
You can iterate all the keys of a Java Map
via its keySet()
method. Here is how iterating the keys of a Java Map
looks:
As you can see, the key Iterator
returns every key stored in a Java Map
, one by one (one for each call to next()
). Once you have the key, you can obtain the element stored for that key using the Map
get()
method.
In the example above, the Iterator next()
method returns an Object - and so does the get()
method. With generic types specified for the Map these methods would have returned the type of the key and value objects respectively. Here is how that would look:
Notice how a generic type is now also specified for the Iterator obtained from map.keySet().iterator()
.
Using a Key For-Each Loop
From Java 5 you can also use the for-each loop to iterate the keys stored in a Java Map
. Here is how that looks:
The effect of the above code is pretty similar to the code shown in the previous section.
If you have specified a generic type for the Java Map, then you can use that type inside the for-each loop. Here is how that looks:
Using a Key Stream
From Java 8 you can use a Java Stream
to iterate the keys of a Java Map
. The Stream
interface is part of the Java Stream API which was added in Java 8. You first obtain the key Set
from the Map
and from that you can get a Stream
. Here is an example of iterating the keys of a Java Map
via a Stream
:
Iterating the Values of a Java Map
It is also possible to just iterate the values stored in a Java Map
. You obtain a Collection
of the values stored in a Map
via the values()
method. You can iterate the values in the Collection
in following ways:
- Using an Iterator
- Using the for-each Loop
- Using a value Stream
All of these options are covered in the following sections.
Using a Value Iterator
The first way to iterate all values stored in a Java Map
is to obtain a value Iterator
instance from the value Set
, and iterate that. Here is how iterating the values stored in a Java Map
using a value Iterator
:
Since a Set
is unordered, you do not have any guarantees about the order in which the values in the value set are iterated. However, if you are using a TreeSet you can control this order still.
Using a Value For-Each Loop
The second method of iterating the values stores in a Java Map
is via the Java for-each loop. Here is how iterating the values of a Java Map
using the for-each loop looks in code:
This example will print out all the values store in the mapA
Map
variable.
Using a Value Stream
The third way to iterate the values stored in a Java Map
is by using a value Stream
, by using the Java Stream API. You first obtain the value Set
from the Map
, and from the value Set
you can obtain the Stream
. Here is an example of iterating the values of a Java Map
via a value Stream
:
Iterating the Entries of a Java Map
It is also possible to iterate all entries of a Java Map
. By entries I mean key + value pairs. An entry contains both the key and value for that entry. Earlier we have only iterated either the keys, or the values, but by iterating the entries we iterate both at the same time.
Like with keys and values, there are two ways to iterate the entries of a Map
:
- Using an Entry Iterator
- Using the for-each loop
Both of these options will be explained in the following sections.
Using an Entry Iterator
The first way to iterate the entries of a Java Map
is via an entry Iterator
obtained from the entry Set
. Here is an example of iterating the entries of Java Map
:
Notice how the key and value can be obtained from each Map.Entry
instance.
Keep in mind that the above code can be made a bit nicer using a Map
typed with Java Generics as shown later in this tutorial.
Using an Entry For-Each Loop
The second way to iterate the entries of a Java Map
is to use a for-each loop. Here is an example of iterating the entries of a Java Map
using a for-each loop:
Notice, that this example too can be made a bit prettier using a generic Map
. Generic Map
instance are explained a bit later in this Java Map tutorial.
Removing Entries From a Java Map
You remove Entries by calling the remove(Object key)
method. You thus remove the (key, value) pair matching the key. Here is an example of removing the entry for a given key in a Java Map
:
After executing this instruction, the Map
referenced by mapA
will no longer contain an entry (key + value pair) for the key key1
.
Removing All Entries
You can remove all entries in a Java Map
using the clear()
method. Here is how that looks:
Replacing an Entry in a Java Map
It is possible to replace an element in a Java Map
using the replace()
method. The replace()
method will only insert the new value if there is already an existing value mapped to the key. If no existing value is mapped to the given key, no value is inserted. This is different from how put()
works, which always insert the value no matter what.
Here is an example of replacing one value with another using the Java Map
replace()
method:
After running this code the Map
instance will contain the String value newer value
for the String key key
.
Reading Number of Entries in Map
You can read the number of entries in a Java Map
using the size()
method. The number of entries in a Java Map
is also referred to as the Map
size - hence the method name size()
. Here is an example of reading the number of entries in a Map using the size()
method:
Checking if a Java Map is Empty
The Java Map
interface has a special method for checking if a Map
is empty. This method is called isEmpty()
and it returns either true
or false
. The isEmpty()
method will return true
if the Map
instance contains 1 or more entries. If the Map
contains 0 entries, isEmpty()
will return false.
Functional Operations in Java Map
The Java Map
interface had a few functional operations added from Java 8. These functional operations make it possible to interact with a Map
in a more functional style. For instance, you pass a Java Lambda Expression as parameter to these functional style methods. You can read more about functional programming in my tutorial about Java Functional Programming .
The functional operation methods are:
- compute()
- computeIfAbsent()
- computeIfPresent()
- merge()
Each of these functional methods will be described in more detail in the following sections.
compute()
The Map
compute()
method takes a key object and a lambda expression as parameters. The lambda expression must implement the java.util.function.BiFunction
interface. Here is an example of calling the Java Map
compute()
method:
The compute()
method will call the lambda expression internally, passing the key object and whatever value is stored in the Map
for that key object, as parameters to the lambda expression.
Whatever value the lambda expression returns is stored instead of the currently stored value for that key. If the lambda expression returns null
, the entry is removed. There will not be a key ->null
mapping stored in the Map
.
In the example above you can see that the lambda expression checks if the value mapped to the given key is null
or not, before calling toString().toUpperCase()
on it.
It the lambda expression throws an exception, the entry is also removed.
computeIfAbsent()
The Map
computeIfAbsent()
method works similarly to the compute()
method, but the lambda expression is only called if no entry exists already for the given key.
The value returned by the lambda expression is inserted into the Map
. If null
is returned, no entry is inserted.
If an exception is thrown by the lambda expression, no entry is inserted either.
Here is an example of calling the Map
computeIfAbsent()
method:
This example actually just returns a constant value - the string 123
. However, the lambda expression could have calculated the value in any way it needed to - e.g. extract the value from another object, or concatenate it from other values etc.
computeIfPresent()
The Map
computeIfPresent()
method works oppositely of computeIfAbsent()
. It only calls the lambda expression passed as parameter to it, if an entry already exists in the Map
for that key. Here is an example of calling the computeIfPresent()
method:
The value returned by the lambda expression will be inserted into the Map
instance. If the lambda expression returns null
, the entry for the given key is removed.
If the lambda expression throws an exception, the exception is rethrown, and the current entry for the given key is left unchanged.
merge()
The Map
merge()
method takes a key, a value, and a lambda expression implementing the BiFunction
interface as parameters.
If the Map
does not have an entry for the key, or if the value for the key is null, the value passed as parameter to the merge()
method is inserted for the given key.
If, however, an existing value is already mapped to the given key, the lambda expression passed as parameter is called instead. The lambda expression thus gets a chance to merge the existing value with a new value. The value returned by the lambda expression is then inserted into the Map
for the given key. If the lambda expression returns null
, the entry for the given key is removed.
Here is an example of calling the Map
merge()
method:
This example will insert the value XYZ
into the Map
if no value is mapped to the key (123
), or if null
is mapped to the key. If a non-null value is already mapped to the key, the lambda expression is called. The lambda expression returns the new value (XYZ
) + the value -abc
, meaning XYZ-abc
.
If an exception is thrown by the lambda expression, the exception is rethrown, and the current mapping for the given key is kept unchanged.
More Details in the Java Map JavaDoc
There is more you can do with a Map
, but you will have to check out the JavaDoc for more details. This text focused on the two most common operations: Adding / removing elements, and iterating the keys and values.
A Map
is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. The Map
interface includes methods for basic operations (such as put
, get
, remove
, containsKey
, containsValue
, size
, and empty
),bulk operations (such as putAll
and clear
), andcollection views (such as keySet
, entrySet
, and values
).
The Java platform contains three general-purpose Map
implementations: HashMap
, TreeMap
, and LinkedHashMap
. Their behavior and performance are precisely analogous to HashSet
, TreeSet
, and LinkedHashSet
, as described in The Set Interface section.
The remainder of this page discusses the Map
interface in detail. But first, here are some more examples of collecting to Map
s using JDK 8 aggregate operations. Modeling real-world objects is a common task in object-oriented programming, so it is reasonable to think that some programs might, for example, group employees by department:
Or compute the sum of all salaries by department:
Or perhaps group students by passing or failing grades:
You could also group people by city:
Or even cascade two collectors to classify people by state and city:
Again, these are but a few examples of how to use the new JDK 8 APIs. For in-depthcoverage of lambda expressions and aggregate operations see the lesson entitledAggregate Operations.
Map Interface Basic Operations
The basic operations of Map
(put
, get
, containsKey
, containsValue
, size
, and isEmpty
) behave exactly like their counterparts in Hashtable
. The following program
generates a frequency table of the words found in its argument list. The frequency table maps each word to the number of times it occurs in the argument list.
The only tricky thing about this program is the second argument of the put
statement. That argument is a conditional expression that has the effect of setting the frequency to one if the word has never been seen before or one more than its current value if the word has already been seen. Try running this program with the command:
The program yields the following output.
Suppose you'd prefer to see the frequency table in alphabetical order. All you have to do is change the implementation type of the Map
from HashMap
to TreeMap
. Making this four-character change causes the program to generate the following output from the same command line.
Similarly, you could make the program print the frequency table in the order the words first appear on the command line simply by changing the implementation type of the map to LinkedHashMap
. Doing so results in the following output.
This flexibility provides a potent illustration of the power of an interface-based framework.
Like the Set
and List
interfaces, Map
strengthens the requirements on the equals
and hashCode
methods so that two Map
objects can be compared for logical equality without regard to their implementation types. Two Map
instances are equal if they represent the same key-value mappings.
By convention, all general-purpose Map
implementations provide constructors that take a Map
object and initialize the new Map
to contain all the key-value mappings in the specified Map
. This standard Map
conversion constructor is entirely analogous to the standard Collection
constructor: It allows the caller to create a Map
of a desired implementation type that initially contains all of the mappings in another Map
, regardless of the other Map
's implementation type. For example, suppose you have a Map
, named m
. The following one-liner creates a new HashMap
initially containing all of the same key-value mappings as m
.
Map Interface Bulk Operations
The clear
operation does exactly what you would think it could do: It removes all the mappings from the Map
. The putAll
operation is the Map
analogue of the Collection
interface's addAll
operation. In addition to its obvious use of dumping one Map
into another, it has a second, more subtle use. Suppose a Map
is used to represent a collection of attribute-value pairs; the putAll
operation, in combination with the Map
conversion constructor, provides a neat way to implement attribute map creation with default values. The following is a static factory method that demonstrates this technique.
Collection Views
The Collection
view methods allow a Map
to be viewed as a Collection
in these three ways:
keySet
— theSet
of keys contained in theMap
.values
— TheCollection
of values contained in theMap
. ThisCollection
is not aSet
, because multiple keys can map to the same value.entrySet
— theSet
of key-value pairs contained in theMap
. TheMap
interface provides a small nested interface calledMap.Entry
, the type of the elements in thisSet
.
The Collection
views provide the only means to iterate over a Map
. This example illustrates the standard idiom for iterating over the keys in a Map
with a for-each
construct:
and with an iterator
:
The idiom for iterating over values is analogous. Following is the idiom for iterating over key-value pairs.
Personal Key Values
At first, many people worry that these idioms may be slow because the Map
has to create a new Collection
instance each time a Collection
view operation is called. Rest easy: There's no reason that a Map
cannot always return the same object each time it is asked for a given Collection
view. This is precisely what all the Map
implementations in java.util
do.
Java Map Value To Key
With all three Collection
views, calling an Iterator
's remove
operation removes the associated entry from the backing Map
, assuming that the backing Map
supports element removal to begin with. This is illustrated by the preceding filtering idiom.
With the entrySet
view, it is also possible to change the value associated with a key by calling a Map.Entry
's setValue
method during iteration (again, assuming the Map
supports value modification to begin with). Note that these are the only safe ways to modify a Map
during iteration; the behavior is unspecified if the underlying Map
is modified in any other way while the iteration is in progress.
The Collection
views support element removal in all its many forms — remove
, removeAll
, retainAll
, and clear
operations, as well as the Iterator.remove
operation. (Yet again, this assumes that the backing Map
supports element removal.)
The Collection
views do not support element addition under any circumstances. It would make no sense for the keySet
and values
views, and it's unnecessary for the entrySet
view, because the backing Map
's put
and putAll
methods provide the same functionality.
Fancy Uses of Collection Views: Map Algebra
When applied to the Collection
views, bulk operations (containsAll
, removeAll
, and retainAll
) are surprisingly potent tools. For starters, suppose you want to know whether one Map
is a submap of another — that is, whether the first Map
contains all the key-value mappings in the second. The following idiom does the trick.
Along similar lines, suppose you want to know whether two Map
objects contain mappings for all of the same keys.
Suppose you have a Map
that represents a collection of attribute-value pairs, and two Set
s representing required attributes and permissible attributes. (The permissible attributes include the required attributes.) The following snippet determines whether the attribute map conforms to these constraints and prints a detailed error message if it doesn't.
Suppose you want to know all the keys common to two Map
objects.
A similar idiom gets you the common values.
Java Get Value From Map
All the idioms presented thus far have been nondestructive; that is, they don't modify the backing Map
. Here are a few that do. Suppose you want to remove all of the key-value pairs that one Map
has in common with another.
Suppose you want to remove from one Map
all of the keys that have mappings in another.
What happens when you start mixing keys and values in the same bulk operation? Suppose you have a Map
, managers
, that maps each employee in a company to the employee's manager. We'll be deliberately vague about the types of the key and the value objects. It doesn't matter, as long as they're the same. Now suppose you want to know who all the 'individual contributors' (or nonmanagers) are. The following snippet tells you exactly what you want to know.
Suppose you want to fire all the employees who report directly to some manager, Simon.
Microsoft office 2013 professional plus product key A Computer comes with different programs which some are unique and others common. There are programs that you will find in almost every computer as they are essential and everybody will need them. Some applications are typical to both professionals and students, and any computer user will need. Microsoft Office 2013 product key is a 25-digit code that’s required to activate a copy of MS Office 2013. The product license key code looks like this: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX If you don’t provide a working key product code, you will not be able to use Microsoft Office 2013. Microsoft office professional plus 2013 key generator download pc. Microsoft Office 2013 Crack With Product Key Generator Updated Version. Microsoft Office 2013 Product Key Generator removes toolbars and allows you to move to a tab in a document as in E-Reader. Videos are better supported You can search, add and display directly in Word. Microsoft Office 2013 Product Key. Office 2013 Product Key is a complete solution for different issues. No doubt, the computer plays the significant role in any field of life. And Office 2013 Product Key download is a whole bundle of features that offers multiple features in each latest version.
Note that this idiom makes use of Collections.singleton
, a static factory method that returns an immutable Set
with the single, specified element.
Once you've done this, you may have a bunch of employees whose managers no longer work for the company (if any of Simon's direct-reports were themselves managers). The following code will tell you which employees have managers who no longer works for the company.
This example is a bit tricky. First, it makes a temporary copy of the Map
, and it removes from the temporary copy all entries whose (manager) value is a key in the original Map
. Remember that the original Map
has an entry for each employee. Thus, the remaining entries in the temporary Map
comprise all the entries from the original Map
whose (manager) values are no longer employees. The keys in the temporary copy, then, represent precisely the employees that we're looking for.
There are many more idioms like the ones contained in this section, but it would be impractical and tedious to list them all. Once you get the hang of it, it's not that difficult to come up with the right one when you need it.
Multimaps
A multimap is like a Map
but it can map each key to multiple values. The Java Collections Framework doesn't include an interface for multimaps because they aren't used all that commonly. It's a fairly simple matter to use a Map
whose values are List
instances as a multimap. This technique is demonstrated in the next code example, which reads a word list containing one word per line (all lowercase) and prints out all the anagram groups that meet a size criterion. An anagram group is a bunch of words, all of which contain exactly the same letters but in a different order. The program takes two arguments on the command line: (1) the name of the dictionary file and (2) the minimum size of anagram group to print out. Anagram groups containing fewer words than the specified minimum are not printed.
There is a standard trick for finding anagram groups: For each word in the dictionary, alphabetize the letters in the word (that is, reorder the word's letters into alphabetical order) and put an entry into a multimap, mapping the alphabetized word to the original word. For example, the word bad causes an entry mapping abd into bad to be put into the multimap. A moment's reflection will show that all the words to which any given key maps form an anagram group. It's a simple matter to iterate over the keys in the multimap, printing out each anagram group that meets the size constraint.
The following program
is a straightforward implementation of this technique.
Running this program on a 173,000-word dictionary file with a minimum anagram group size of eight produces the following output.
Many of these words seem a bit bogus, but that's not the program's fault; they're in the dictionary file. Here's thedictionary file
we used.It was derived from the Public Domain ENABLE benchmark reference word list.