Group by two lists in one map using lambda I've got two collections: collection of rules, and collection of keys that can handle specific rules. Key have method boolean canHandle(Rule) to check whether specific key can handle specific rule or not.

I need to gather these two collections into single map Map&lt;Key, List&lt;Rule&gt;&gt; bycanHandle` predicate method. I've done this so far:

Map&lt;Key, List&lt;Rule&gt;&gt; keyToRulesMapping = rules.parallelStream()
        .collect(Collectors.groupingBy(rule -&gt; keys.stream()
                .filter(key -&gt; key.canHandle(rule))
                .findFirst().get()));


The thing I don't like in this approach is number of traverse in key list to get the right key. In best case I have only one key that handles all rules (\$O(N)\$ where N is the number or rules). In worst case I have each key associated with it's own unique rule (becomes \$O(N^2)\$). I'm asking is there a better way to match these two lists or my approach is good enough?
This does not look horribly wrong to me. There are some issues though:


groupingBy I presume is a static import from Collectors? You should make these things more obvious. In fact, I dislike the static imports for most things.....
you don't show much about ruleKeys.


The style otherwise looks good.

The concept you are solving, given the information you have given, is being solved in what amounts to a reasonably efficient manner, all things considered. It is an \$O(nm)\$ solution, if you double either the number of rules, or number of keys, your solution will take twice as long, and if you double both, the solution will take 4 times as long.

If you do this just once and then reuse the Mapping, then it should be fine. If you have fewer than say 100 members in each of the rules/keys, then you should be fine.

If you have more data than that then you should consider building up the data directly in to the map at the same time as you initially populate the rules/keys.

So, you are right to not like the solution because it scales badly, but, if your data is small, be pragmatic and not worry about it too much in this instance.