英文:
Remove elements from List of objects by comparing with another array in Java
问题
我有一个订阅列表
subscriptions = [
{
code: "Heloo",
value: "一些值",
reason: "一些原因"
},
{
code: "Byeee",
value: "一些再见",
reason: "一些再见"
},
{
code: "World",
value: "一些世界",
reason: "一些世界"
}
]
我还有一个取消订阅列表:
unsubscribe: ["Heloo", "World"]
我想通过比较这两个数组来取消订阅订阅列表中的元素
最终结果:
subscriptions = [
{
code: "Byeee",
value: "一些再见值",
reason: "一些再见原因"
}
]
以下是我的解决方案:
List
for (String products : subscriptions) {
newList.add(products.code);
}
if (!newList.containsAll(unsubscribe)) {
log.error("有些产品未订阅");
}
for (int i = 0; i < subscriptions.size(); i++) {
if(unsubscribe.contains(subscriptions.get(i).code)) {
subscriptions.remove(i);
}
}
这个方法可能还有优化的空间,我正在寻找一个更好/更优化的解决方案。
英文:
I have a list of subscriptions
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"
}
]
I have another list of unsubscriptions:
unsubscribe : ["Heloo","World"]
I want to unsubscribe elements in the subscriptions by comparing these two arrays
Final Result :
subscriptions = [
{
code : "Byeee",
value:"some byee value",
reason : "some byee reason"
}
]
Below is my solution :
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);
}
}
This could be better . I am looking for a better/optimized solution.
答案1
得分: 3
使用removeIf
会显著简化您的代码:
List<Subscription> subscriptions = ... ;
List<String> unsubscribe = ...;
subscriptions.removeIf(s -> unsubscribe.contains(s.code));
英文:
Using removeIf
will clean up your code considerably:
List<Subscription> subscriptions = ... ;
List<String> unsubscribe = ...;
subscriptions.removeIf(s -> unsubscribe.contains(s.code));
答案2
得分: 0
你也可以使用流来完成:
List<String> newList = subscriptions
.stream()
.filter(it -> !unsubscribe.contains(it.code))
.collect(Collectors.toList());
英文:
You can also do it with streams:
List<String> newList = subscriptions
.stream()
.filter(it -> !unsubscribe.contains(it.code))
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论