Waqas Baig
Waqas Baig

Reputation: 79

Compare Set<String> with Map<Object> to get Map value in Java 8

I have Set<String> requests = new HashSet<>() and added dynamically some string values in it.

I have Map<TargetSystems> targetSystems = new HashMap<>();, targetSystems with name key and targetSystems object in value.

So I need those targetSystems from Map which are in in Set.

Like Map.put("LMS", TargetSystems) and many more from Database. Set<String> requests has same target systems name. How can I achieve this in Java 8. I don't want to execute forEach loop into Set because I have already created thread list and looping on that. So I need solution in Java 8 with Stream.filter kind of.

Thanks in advance.

Upvotes: 1

Views: 1046

Answers (3)

Waqas Baig
Waqas Baig

Reputation: 79

I have already got an answer and code below please see it's working fine. Case was that, if we have Map<Object(Its entity class type)> targetSystems and put targetSystems entity objects by the name of it's entity key. Now I have multiple request by the same name exists in targetSystems Map, so I need to equalized that hashset value with hashmap. I achieved as under:

Object[] objects = Map<String, Object>.values().stream().filter(ts -> Set.contains(ts.getName())).toArray();

I get Object[] type, so I can get my targetSystems value from Map as easy as I like.

Thanks all of you for your kind answers and thanks to stack Overflow.

Upvotes: 0

Qwer Izuken
Qwer Izuken

Reputation: 639

If you want to filter your targetSystems map:

Map<String, TargetSystems> targetSystemsFiltered = targetSystems.entrySet().stream()
     .filter(entry -> requests.contains(entry.getKey()))
     .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

If you want just to get filtered targetSystem objects:

Set<TargetSystems> targetSystemsFromSet = targetSystems.entrySet().stream()
      .filter(entry -> requests.contains(entry.getKey()))
      .map(Map.Entry::getValue)
      .collect(Collectors.toSet());

Upvotes: 0

VGR
VGR

Reputation: 44414

I am going to assume that you meant Map<String, TargetSystems>.

You can make a copy of the Map, and use Set.retainAll to limit which entries are in it:

Map<String, TargetSystems> copy = new HashMap<>(targetSystems);
copy.keySet().retainAll(requests);

Collection<TargetSystems> systemsForRequests = copy.values();

Upvotes: 1

Related Questions