List<int[]> bigList = new ArrayList<int[]>();
List<int[]> smallList = new ArrayList<int[]>();
我需要生成一个 int[] 类型的列表,其中公共(public)数组构成两个列表。(值应该相等,不使用 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
用于集合操作。源和结果排序的语义以及如何处理源列表中的重复项未指定。
关于java-8 - Java 流的两个 List<int[]> 类型的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31451891/