Java - 包含检查数组列表中的所有项目是否满足条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32305478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - contains check all items in an arraylist meet a condition
提问by Prabu
myArrayList = {"Method and apparatus","system and method for the same","drive-modulation method"," METHOD FOR ORTHOGONAL"}
How can i check if all the Items (myArrayList) contains a word "method" (irrespective of case)
如何检查所有项目(myArrayList)是否包含“方法”一词(不考虑大小写)
boolean method return true
if all the items contain the word, else its false
true
如果所有项目都包含该单词,则布尔方法返回,否则返回false
采纳答案by Suresh Atta
Iterate and use contains. Remove the or conditions if you want case specific.
迭代并使用 contains。如果您想要特定于案例,请删除或条件。
public static boolean isListContainMethod(List<String> arraylist) {
for (String str : arraylist) {
if (!str.toLowerCase().contains("method")) {
return false;
}
}
return true;
}
回答by Kristian Vukusic
public boolean listContainsAll(List<String> list) {
for (String item : list) {
if (!item.toLowerCase().contains("method")) {
return false;
}
}
return true;
}
回答by Fran Montero
Simple loop checking condition, added white chars for avoiding wrong words as 'somewordmethod':
简单的循环检查条件,添加了白色字符以避免错误的单词为“somewordmethod”:
boolean result = true;
for (String elem : yourList) {
if (!elem.toLowerCase().contains(" method ")) {
result = false;
break;
}
}
return result;
return result;
回答by Uma Kanth
You will have to check for the whole arraylist and return false if there is a string without that word.
您将不得不检查整个数组列表,如果有一个没有该词的字符串,则返回 false。
public static void main(String[] args) {
ArrayList<String> list = new ArrayList();
list.add("I have the name");
list.add("I dont have the number");
list.add("I have a car");
System.out.println(check(list, "I"));
}
private static boolean check(ArrayList<String> list, String word) {
// TODO Auto-generated method stub
for(String s : list)
if(!list.contains(word))
return false;
return true;
}
回答by chengpohi
In Java8, you can use streamwith matchingto simplify your code.
在Java8 中,您可以使用带有匹配的流来简化您的代码。
return arrayList.stream().allMatch(t -> t.toLowerCase().contains("test"));
回答by SaviNuclear
ArrayList
implements the List
Interface.
ArrayList
实现List
接口。
If you look at the Javadoc for List
at the contains method you will see that it uses the equals()
method to evaluate if two objects are the same.
如果您查看List
contains 方法的 Javadoc,您将看到它使用该equals()
方法来评估两个对象是否相同。
int tempCount = 0;
for (String str : arraylist) {
if(str.conatains("method") || str.conatains("Method")) {
tempCount++;
}
}
if(tempCount == arraylist.size()) {
return true;
} else {
return false;
}