I need create inverse map - select unique values and for them find keys. Seems that only way is to iterate all key/value pairs, because entrySet returns set of so value not unique? Thanks.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
It's one way at least. Here's an example:
In case of non-unique values, this algorithm will map the last value found to it's key. (Since the iteration order is undefined for most maps, this should be as good as any solution.)
If you really do want to keep the first value found for each key, you could change it to
I would give another approach to this problem giving an extra dimension: duplicate values in EntrySet.
T result will be that:
Take a look at Google Guava BiMap.
Example usage
To get an inverted form of a given map in java 8:
Example usage
Apache Commons Collections also provides a
BidiMap
interface for bi-directional maps, along with several implementations.BidiMap JavaDoc
The values in a map may not be unique. But if they are (in your case) you can do as you wrote in your question and create a generic method to convert it:
Java 8:
Example of usage:
Side note: the
put(.., ..)
method will return the the "old" value for a key. If it is not null you may throw anew IllegalArgumentException("Map values must be unique")
or something like that.