我有两个对象列表 dbAssets
和assetVOS
.
我想要使用流通过某些属性(在我的例子中是 getSecName()
)获得共同元素(以及差异)。
我尝试过以下方法:
dbAssets.stream().map(SomeClass::getSecName)
.filter(dbAssetName -> assetVOS.stream()
.map(SomeClass::getSecName)
.anyMatch(assetVOSName -> dbAssetName.equals(assetVOSName)))
.collect(Collectors.toList());
但我收到以下错误:
Incompatible types. Required
List<SomeClass>
but 'collect' was inferred to R: no instance(s) of type variable(s) exist so thatString
conforms toSomeClass
inference variable T has incompatible bounds: equality constraints:SomeClass
lower boundsString
最佳答案
由于您正在映射您的SomeClass
实例进入String
s,您的流管道会生成 List<String>
,不是List<SomeClass>
.
获得List<SomeClass>
,尝试这样的事情:
List<SomeClass> output =
dbAssets.stream()
.filter(obj -> assetVOS.stream()
.map(SomeClass::getSecName)
.anyMatch(assetVOSName -> obj.getSecName ().equals(assetVOSName)))
.collect(Collectors.toList());
关于java - 使用 Streams 通过特定属性获取两个列表之间的共同元素和差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72948870/