mladirazvijac
mladirazvijac

Reputation: 67

How to filter, using stream, Map<String, Object> by List<String> which contains keys

I have Map<String, Object> which has to be become Map<String, String>. Filtering should be done by List<String>.

That list contains keys of map elements that should be in new map.

For this I need to use streams.

Map<String, Object> oldMap;
List<String> keysForFiltering;
Map<String, String> newMap;

Upvotes: 0

Views: 7331

Answers (2)

since you have a map then you can get the stream of that and use a custom predicate, that predicate need to check if the Entry.key is present in your list or not

Map<String, String> myMap = new HashMap<>();
myMap.put("A", "fortran");
myMap.put("B", "java");
myMap.put("C", "c++");
myMap.put("D", "php");

List<String> keysForFiltering = Arrays.asList("A", "C");

Predicate<Entry<String, String>> myPredicate = t -> keysForFiltering.contains(t.getKey());

Map<String, String> filteredMap = myMap
        .entrySet().stream().filter(myPredicate)
        .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));

System.out.println(filteredMap);

Upvotes: 1

Eran
Eran

Reputation: 393771

It would be more efficient if the filter would operate on a Set of keys instead of a List of keys, since searching a Set is more efficient than searching a List.

Map<String, String> newMap =
    oldMap.entrySet()
          .stream()
          .filter(e -> keysForFiltering.contains(e.getKey()))
          .collect(Collectors.toMap(Map.Entry::getKey,
                                    e -> e.getValue().toString()));

Upvotes: 2

Related Questions