[英]Remove elements from List of objects by comparing with another array in Java
我有一個訂閱列表
subscriptions = [
{
code : "Heloo",
value:"some value",
reason : "some reason"
},
{
code : "Byeee",
value:"some byee",
reason : "some byee"
},
{
code : "World",
value:"some World",
reason : "some world"
}
]
我還有另一個取消訂閱列表:
unsubscribe : ["Heloo","World"]
我想通過比較這兩個數組來取消訂閱中的元素
最后結果 :
subscriptions = [
{
code : "Byeee",
value:"some byee value",
reason : "some byee reason"
}
]
以下是我的解決方案:
List<String> newList = new ArrayList<>();
for (String products : subscriptions) {
newList.add(products.code);
}
if (!newList.containsAll(unsubscribe) {
log.error("Few products are not subscribed");
}
for (int i = 0; i < subscriptions.size(); i++) {
if(unsubscribe.contains(subscriptions.get(i).code)) {
subscriptions.remove(i);
}
}
這可能會更好。 我正在尋找更好/優化的解決方案。
你也可以用流來做到這一點:
List<String> newList = subscriptions
.stream()
.filter(it -> !unsubscribe.contains(it.code))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.