Reputation: 165
how i can get the Key from my Value?
My HashMap:
public static final Map<String, List<String>> Server = new HashMap<>();
my attempt:
public static Object getKeyFromValue(String value) {
for (Object o : Server.keySet()) {
if (Server.get(o).equals(value)) {
return o;
}
}
return null;
}
It dosent work, because the Value is a List.
Upvotes: 1
Views: 8416
Reputation: 401
Just changing from equals to contains works. and all remains same
public static Object getKeyFromValue(String value) {
for (Object o : Server.keySet()) {
if (Server.get(o).contains(value)) {
return o;
}
}
return null;
}
Upvotes: 0
Reputation: 37645
When you iterate over a Map
, if you need both the key and the value it's better to iterate over the entrySet
rather than the keySet
.
public static String getKeyFromValue(String value) {
for (Map.Entry<String, List<String>> e : Server.entrySet()) {
if (e.getValue().contains(value)) {
return e.getKey();
}
}
return null;
}
This should work, but there are 3 things I don't like about it (apart from Server
beginning with a capital letter).
contains
for many List
implementations (including ArrayList
and LinkedList
) is slow, because it is a linear search. It may better to use HashSet
instead.value
occurs in more than one list in the map, the returned key could be any of multiple answers. It may be better for the name of the method to indicate this (e.g. getAnyKeyForValue
).Optional<String>
rather than using null
to mean that the value was not found.A Java 8 solution, taking all of these points into consideration and taking advantage of parallelism would be
public static Optional<String> getAnyKeyForValue(String value) {
return Server.entrySet()
.parallelStream()
.filter(e->e.getValue().contains(value))
.map(Map.Entry::getKey)
.findAny();
}
Upvotes: 0
Reputation: 85781
Use List#contains
:
if (Server.get(o).contains(value)) {
//...
}
Upvotes: 1