简体   繁体   中英

Java 8 stream Map<String, Map<String, Integer>> return map values if root map key contains

I have a map of maps:

Map<String, Map<String, Integer>> rootMap

and I want to return the rootMap values Map<String, Integer> if rootMap key contains stringValue using stream.

I tried:

rootMap.entrySet().stream().filter(e -> e.getKey().contains(stringValue)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

but I get Map<Object, Object> instead of Map<String, Integer>

Update #1

// it's a class with one field and a helper method
// @Data is a Lombok annotation
@Data
public class A {

    public Map<String, Map<String, Integer>> rootMap;

    public Map<String, Integer> getValuesByKey(String stringValue) {
        return rootMap.entrySet().stream().filter(e -> e.getKey().contains(stringValue)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    }
}

Here is your expression:

rootMap.entrySet()
    .stream()
    .filter(e -> e.getKey().contains(stringValue))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Here is your goal:

and I want to return the rootMap values Map<String, Integer> if rootMap key contains stringValue using stream.

Recall that map keys must be unique. You can't have more than one Map.Entry of the same instance with the same key. Therefore, you can obtain the Map<String, Integer> corresponding to the key in rootMap whose value is stringValue as follows:

rootMap.entrySet()
    .stream()
    .filter(e -> e.getKey().equals(stringValue))
    .map(e -> e.getValue())
    .findAny()
    .get();

To defend against an error in the case that the key does not exist in rootMap you can use this version:

rootMap.entrySet()
    .stream()
    .filter(e -> e.getKey().equals(stringValue))
    .map(e -> e.getValue())
    .findAny()
    .orElse(Collections.emptyMap());

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM