Andy897
Andy897

Reputation: 7133

Java stream to find occurrences in a list

I am trying to write this code using Java streams which does the following -

Take a List of KeyValuePairs and a ListOfValues, and populates a Map of <Value, boolean> where Value comes from ListOfValues and boolean is set to true or false based on whether value was present in ListOfKeyValuePairs.

I am starting something like:

keyValuePairs.stream().map(KeyValuePair::getValue) ... 

But not able to complete it :(

Example:

List<KeyValuePairs> has {(1, A1), (2,A2), (3,A3)}
ListofValues has {A1,A3}

End result: Map with values : A1, true and A3, true

Upvotes: 1

Views: 106

Answers (1)

Andrew
Andrew

Reputation: 49606

List<KeyValuePairs> can be transformed into a Set<Value> to speed up further lookups:

var set = pairs.stream()
               .map(KeyValuePair::getValue)
               .collect(Collectors.toSet());

Then, if the resulting map shouldn't contain elements that haven't been found in pairs, filter them out by set::contains:

var map = list.stream()
              .filter(set::contains)
              .collect(Collectors.toMap(Function.identity(), i -> true));

If the resulting map should contain every element from list, whether or not they have been found:

var map = list.stream()
              .collect(Collectors.toMap(Function.identity(), set::contains));

Upvotes: 3

Related Questions