Hmm, good question.  I first thought the behavior you saw is right, since
you're not working with sets (and sets do work -- they're all I've used
with intersect).  But it's worth noting, this is not what Apache's
CollectionUtils.intersection(java.lang.Iterable,
java.lang.Iterable)
<http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html#intersection(java.lang.Iterable,
java.lang.Iterable)> does.

@Grab(group='org.apache.commons', module='commons-collections4',
version='4.0')
import org.apache.commons.collections4.CollectionUtils

def a = [1,1]
def b = [1,2,3]
assert CollectionUtils.intersection(a, b) == [1]

-Keegan


On Tue, Jun 9, 2015 at 2:35 PM, Shil Sinha <[email protected]> wrote:

> It happens when the larger iterable (larger as a collection) is not a set,
> and there are duplicates in the smaller iterable.
>
> Example:
>
> def a = [1,1]
> def b = [1,2,3]
> assert a.intersect(b) == [1,1]
>
> Set a = [1,2,3].toSet()
> def b = [1,1]
> assert a.intersect(b) == [1].toSet()
>
>
> The behavior is due to the implementation, where all elements of the
> larger iterable are first added to a treeset, after which all elements of
> the smaller iterable that are contained in the treeset are added to the
> result collection. As the result is a collection similar to
> the larger iterable, there will not be duplicates if the larger collection
> is a set.
>
> On Tue, Jun 9, 2015 at 1:19 PM, Keegan Witt <[email protected]> wrote:
>
>> I've not had trouble with intersect() myself.  Under what circumstances
>> did you observe the duplicates?  Can you give an example?
>>
>> -Keegan
>>
>> On Tue, Jun 9, 2015 at 11:13 AM, Peter Ledbrook <[email protected]>
>> wrote:
>>
>>> Hi,
>>>
>>> While implementing and testing an intersect() method for CharSequence, I
>>> noticed that Iterable.intersect() may return duplicate elements. Is that
>>> intentional? It's not the behaviour I would expect.
>>>
>>> Thanks,
>>>
>>> Peter
>>>
>>
>>
>

Reply via email to