0

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;
1
  • Non Java 8 solution. Just simple foreach iteration. Commented Aug 3, 2017 at 7:53

2 Answers 2

2

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()));
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.