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??
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With