java 流的两个 List<int[]> 类型的交集
Intersection of two List<int[]> types by java streams
List<int[]> bigList = new ArrayList<int[]>();
List<int[]> smallList = new ArrayList<int[]>();
我需要生成一个 int[] 类型的列表,其中公共数组构成两个列表。(值应该相等,不使用 contains())
如何在 java 流中有效地做到这一点?
如果它真的必须是流式解决方案,这里有一个:
List<int[]> intersection=bigList.stream().map(IntBuffer::wrap)
.filter(b->smallList.stream().map(IntBuffer::wrap).anyMatch(b::equals))
.map(IntBuffer::array)
.collect(Collectors.toList());
但是执行最多 bigList.size()×smallList.size() 操作并不是真正有效。因此,强烈建议使用中间 Set
存储,而不是即时执行所有操作:
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());
请注意,您不应使用 List
进行集合运算。源和结果排序的语义以及如何处理源列表中的重复项未指定。
List<int[]> bigList = new ArrayList<int[]>();
List<int[]> smallList = new ArrayList<int[]>();
我需要生成一个 int[] 类型的列表,其中公共数组构成两个列表。(值应该相等,不使用 contains())
如何在 java 流中有效地做到这一点?
如果它真的必须是流式解决方案,这里有一个:
List<int[]> intersection=bigList.stream().map(IntBuffer::wrap)
.filter(b->smallList.stream().map(IntBuffer::wrap).anyMatch(b::equals))
.map(IntBuffer::array)
.collect(Collectors.toList());
但是执行最多 bigList.size()×smallList.size() 操作并不是真正有效。因此,强烈建议使用中间 Set
存储,而不是即时执行所有操作:
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());
请注意,您不应使用 List
进行集合运算。源和结果排序的语义以及如何处理源列表中的重复项未指定。