I'm fairly new to java in general so help is very appreciated.
I have a structure like this:
private Map<String, List<String>> campaign = new Hashmap<>();
This hashmap has values like this:
campaign = {
"John": {["1234"]},
"Doe": {["5555","2222"]},
"Smith": {["Smith"]}
}
I'm trying to filter the key of this hashMap when one of the elements matches an element of the list.
I've tried this so far based on similar solutions I found:
public String getKey(String id) {
campaign.entrySet().stream()
.filter(map -> map.getValue().stream().
anymatch(list -> list.contains(id)))
.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue() ))
}
// I see toMap is not what I need but don't know what to use
I expecto to get: getKey(1234) = "John"
CodePudding user response:
You don't need to collect to a map, but to the key(s) you found.
.filter(entry -> entry.getValue().contains(id))
.map(Entry::getKey)
.collect(toSet());
You might find more than one key, hence the Set
.
CodePudding user response:
You may want to use findAny()
:
public String getKey(String id) {
return campaign
.entrySet()
.stream()
.filter(map -> map
.getValue()
.stream()
.anyMatch(list -> list.contains(id))
)
.map(Entry::getKey)
.findAny()
.orElse(null);
}
anyMatch()
returns an Optional
that contains any value of the (filtered) Stream
(if it is present).
If you want to get the first element in the Stream
, you could use findFirst
instead but order is not relevant in most Map
s anyways.
With .map
, you can map the entry to its key.
In case you want to return all keys, you could use methods like toList
or .toSet
.
With orElse(null)
, you specify that null
should be used if no matching entry/key was found.
As an alternatives to orElse
, you could return the Optional
or use orElseThrow
if the value needs to be present.