I have Map<Long, Map<String, String>> map
, and I have to filter that by key and further get only value. I'm trying to do some like that:
Map<Object, Object> resultMap = map.entrySet().stream()
.filter(x -> x.getKey().equals(filterValue))
.map(Map.Entry::getValue).collect(Collectors.toMap(k -> k,v -> v));
But I got Map<Object, Object>
map instead of Map<String, String>
.
Maybe, there is some better way to do it.
You should set values of map to specific types in collector
.collect(Collectors.toMap(Object::toString, Object::toString))
The following should work as you need:
Map<String, String> resultMap = map.entrySet().stream()
.filter(x -> x.getKey().equals(filterValue))
.flatMap(entry -> entry.getValue().entrySet().stream())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
From map.entrySet().stream().filter(x -> x.getKey().equals(filterValue))
, it could be understood that filterValue
is a long
. There is no need to stream a map to filter out the values matching a particular key. Because map keys are unique, and there will be only one matching key. You could have just used:
Map<String, String> result = map.get(filterValue);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.