Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify that all key/value pairs in a Map are present in another Map

I have a List of objects containing a Map. The object looks like this :

public class SwiftObject {
    private Map<String, String> metadata;
    ...
}

I'm trying to filter my objects based on the keys and values stored in their Map.
My filter criteria are contained in another Map.
I'd like to filter and keep all the objects which Map has all key/value contained in the filter Map.

This is the code I wrote :

List<? extends SwiftObject> swiftObjects = documentStore.listAllObjects(container);
Map<String, String> searchMetadata = gssDocument.getMetadataMap();
List<SwiftObject> filteredSwiftObjects = swiftObjects.stream()
            .filter(swiftObject ->
                    searchMetadata.entrySet().stream()
                    .allMatch(entry -> entry.getValue().equals(swiftObject.getMetadata().get(entry.getKey())))
                    )
            .collect(Collectors.ToList());

Is it the right way to do this or can it be refactored/optimized?
The searchMetadata map does not contain null values

like image 564
bobuns Avatar asked Oct 08 '15 19:10

bobuns


1 Answers

Use Map.equals(Map other) to check if both maps contain the same mappings. If you just need to check if a map is a subset of another map, use map.entrySet().containsAll(other.entrySet()).

like image 98
Audrius Meškauskas Avatar answered Nov 03 '22 20:11

Audrius Meškauskas