Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection of two List<int[]> types by java streams

List<int[]> bigList = new ArrayList<int[]>();
List<int[]> smallList = new ArrayList<int[]>();

I need to generate a List of type int[] with the common arrays form both the lists.(values should be equal , not using the contains())

How to do it efficiently in java streams??

like image 788
jeDy Avatar asked Sep 01 '26 05:09

jeDy


1 Answers

If it really has to be a stream solution, here’s one:

List<int[]> intersection=bigList.stream().map(IntBuffer::wrap)
    .filter(b->smallList.stream().map(IntBuffer::wrap).anyMatch(b::equals))
    .map(IntBuffer::array)
    .collect(Collectors.toList());

but it isn’t really efficient by performing up to bigList.size()×smallList.size() operations. So instead of doing everything on-the-fly, resorting to an intermediate Set storage is strongly recommended:

Set<IntBuffer> bigSet=bigList.stream().map(IntBuffer::wrap).collect(Collectors.toSet());
List<int[]> intersection=smallList.stream().map(IntBuffer::wrap)
     .filter(bigSet::contains).map(IntBuffer::array).collect(Collectors.toList());

Note that you shouldn’t use List for set operations. The semantics of source and result ordering and how to handle duplicates within the source lists are unspecified.

like image 113
Holger Avatar answered Sep 04 '26 14:09

Holger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!