Find mapped value of map
Because of how a map
is designed, you'll need to do the equivalent of a search on unordered data.
for (auto it = someMap.begin(); it != someMap.end(); ++it)
if (it->second == someValue)
return it->first;
Finding an element in map by its value
You can use the member function find
to search for key only. To search for a value, you can use a std::find_if
with a lambda function (if you use C++11), or to traverse the map (ok in previous C++ version):
for (HandleMap::const_iterator it = map.begin(); it != map.end(); ++it) {
if (it->second == name) return it->first;
}
// or value not found
On the other hand, if searching for a value is a very common operation, you may want to have two maps: std::unordered_map<Handle, std::string>
and std::unordered_map<std::string, Handle>
. In that case, you have to make sure you perform insertions, deletions, etc. in both maps to keep then synchronized.
How to create map with mapped value?
You are correct that no lambda will work there. There are a few alternative options, but the one I'd use would be:
Map<String, String> result = inputStrings.stream()
.map(str -> new AbstractMap.SimpleImmutableEntry<>(str, hashFunc(str)))
.filter(entry -> entry.getValue().startsWith("00"))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
(If I weren't collecting to a Map
, I would create my own custom tuple type appropriate for the use case rather than using Map.Entry
, but here Map.Entry
is a sufficient type.)
How to get values and keys from HashMap?
To get all the values from a map:
for (Tab tab : hash.values()) {
// do something with tab
}
To get all the entries from a map:
for ( Map.Entry<String, Tab> entry : hash.entrySet()) {
String key = entry.getKey();
Tab tab = entry.getValue();
// do something with key and/or tab
}
Java 8 update:
To process all values:
hash.values().forEach(tab -> /* do something with tab */);
To process all entries:
hash.forEach((key, tab) -> /* do something with key and tab */);
Finding Matching Keys and Values in a Map
You are putting all the values from first to output by passing it to the constructor.
Map<String, Integer> output = new HashMap<String, Integer>(first); // you are passing first to the constructor.
You don't need to create another Set, keySet() method returns set so the below lines not required.
Set<String> keyFirst = new HashSet<String>(); // stores all the keys for first
for (String key: first.keySet()) { // goes through each key in input
keyFirst.add(key); // adds all keys from first into keyFirst
}
Here's the correct implemetataion.
// we need to store the keys, then get the values in common, then put the key/map into map
public static Map<String, Integer> intersect(Map<String, Integer> first, Map<String, Integer> second) {
Map<String, Integer> output = new HashMap<String, Integer>(); // combined output
// goes through each key in common and checks to see if they reference to the same value
Iterator<String> keyFirstItr = first.keySet().iterator();
while (keyFirstItr.hasNext()) {
String keyTemp = keyFirstItr.next();
if (first.get(keyTemp).equals(second.get(keyTemp))) { // If same key, same value mapped
output.put(keyTemp, first.get(keyTemp)); // add key value to map
}
}
return output;
}
how to use map::find on map of maps
To find a value in a map, you cannot use find
member function, which finds a key. However, you can find a value, e.g., by using std::find_if
with a custom comparator:
using value_t = std::map<std::string, std::string>;
using key_t = std::string;
using map_t = std::map<key_t, value_t>;
map_t m { { "key" , { { "hello", "world" } } } };
value_t v { { "hello", "world" } }; // value to be found
auto iter = std::find_if(m.begin(), m.end(),
[&v](const auto& e){ return e.second == v; });
std::cout << (iter != m.end()) << std::endl;
Live demo: https://wandbox.org/permlink/1b0bjbnnPY8E0uiU
Note that this will work since C++14. In C++11, you need to write:
auto iter = std::find_if(m.begin(), m.end(),
[&v](const map_t::value_type& e){ return e.second == v; });
UPDATE
It's still kind-of unclear to me what you are trying to achieve. If you need a reference to the inner-most value only if it's both-level keys exist, then you can do (C++17 syntax):
if (auto i1 = m.find("key"); i1 != m.end())
if (auto i2 = i1->second.find("hello"); i2 != i1->second.end())
std::cout << i2->second << std::endl; // same as m["key"]["hello"] here but faster
How to map values in a map in Java 8?
You need to stream the entries and collect them in a new map:
Map<String, String> result = map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getKey, e -> String.valueOf(e.getValue()));
Related Topics
How to Get a Certain Element in a List, Given the Position
How to Improve Link Performance for a Large C++ Application in VS2005
How to Use the _Attribute_((Visibility("Default")))
How to Erase & Delete Pointers to Objects Stored in a Vector
Double-Checked Lock Singleton in C++11
How to Calculate Perspective Transform for Opencv from Rotation Angles
Deterministic Builds Under Windows
Can't Downcast Because Class Is Not Polymorphic
Name of Process for Active Window in Windows 8/10
Thread Safety of Mpi Send Using Threads Created with Std::Async
Debug and Release Library Linking with Cmake (Visual Studio)
C++: Pointer to Monomorphic Version of Virtual Member Function
Whats the Right Approach to Return Error Codes in C++
C Preprocessor MACro Specialisation Based on an Argument
Calling Derived Class Function from Base Class
A Simple Hello World Npapi Plugin for Google Chrome
What Use Are Const Pointers (As Opposed to Pointers to Const Objects)