英文:
Java8 lambda remove element from List<?> and update the boolean flag value
问题
我需要在从List<String>中移除某个对象时,设置一个标志`nameRemoved=true`。
这是我目前使用的传统方法。
List<String> list = new ArrayList<String>();
if (list.contains("abc")) {
list.remove("abc");
nameRemoved = true;
}
我可以使用以下方法从列表中删除元素,但如何使用lambda语法设置标志值为`nameRemoved=true`呢?
List<String> list = new ArrayList<String>();
list.removeIf(name -> name.equalsIgnoreCase("abc"));
英文:
I've to set one flag nameRemoved=true
, when I remove some object from the List<String>
This what traditional approach I'm using here.
List<String> list = new ArrayList<String>();
if (list.contains("abc")) {
list.remove("abc");
nameRemoved=true
}
I can remove element from the list using below but how can I also set the flag value to nameRemoved=true
using lambda syntaxes ?
List<String> list = new ArrayList<String>();
list.removeIf(name -> name.equalsIgnoreCase("abc"));
答案1
得分: 7
根据op的要求,我把我的评论作为一个回答。
因为removeIf
在任何元素被移除时会返回true,你可以根据结果设置你的标志。
nameRemoved = list.removeIf(name -> name.equalsIgnoreCase("abc"))
或者更安全并且使用方法引用:
nameRemoved = list.removeIf("abc"::equalsIgnoreCase);
编辑:
正如@Holger评论的那样,这个答案只关注如何用removeIf
替换代码。但这段代码与第一个代码有很大不同。第一个代码只会移除列表中与给定字符串完全匹配的一个元素。而我提供的代码会移除所有忽略大小写匹配的元素。
英文:
As op requested I put my comment as an answer.
Because removeIf return true if any element was removed you can set your flag based on the result.
nameRemoved = list.removeIf(name -> name.equalsIgnoreCase("abc"))
Or safer and with a method reference:
nameRemoved = list.removeIf("abc"::equalsIgnoreCase);
EDIT:
As @Holger commented this answer only focus on how to replace the code with the removeIf. But this code is quite different from the first one. The first one remove only one element from the list that match exactly the given string. The one I provided will remove all element that match ignoring the case.
答案2
得分: 3
RemoveIf
返回一个布尔值,因此您可以这样做:
List<String> list = new ArrayList<String>();
boolean nameRemoved = list.removeIf(name -> "abc".equalsIgnoreCase(name));
或者
List<String> list = new ArrayList<String>();
boolean nameRemoved = list.removeIf("abc"::equalsIgnoreCase);
链接:https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-
英文:
RemoveIf
returns a boolean so you can do this:
List<String> list = new ArrayList<String>();
boolean nameRemoved = list.removeIf(name -> "abc".equalsIgnoreCase(name));
or
List<String> list = new ArrayList<String>();
boolean nameRemoved = list.removeIf("abc"::equalsIgnoreCase);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论