Reputation: 89
I want to use a for loop like this:
`button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Object.setList();
for(int i = 0; i < Object.getList.size(); i++)
if(!Object.getList.get(i).trim().toLowerCase().contains("hello")) {
Toast.makeText(getContext(), "List does not contain "Hello", Toast.LENGTH_LONG).show;
}
}`
This is my model:
public class Object {
private ArrayList<String> mArrayList;
public void setList() {
mArrayList = new Arraylist<>();
mArrayList.add("Random Message");
mArrayList.add("ZZZZ")
}
public ArrayList<String> getList() {
return mArrayList;
}
}
I still keep getting the Toast message, but it works just fine when i use:
if(!Object.getList().toString.trim().toLowerCase().contains("hello"))
Upvotes: 1
Views: 2943
Reputation: 976
If your aim is to check if each string in the list does not have "hello" and show toast each time then you can do so :
Object.getList().forEach(el -> {
if(!el.toLowerCase().contains("hello")){
// show toast
}
})
If your aim is to check if each string in the list does not have "hello" and show toast only once the do so :
if(Object.getList().stream().noneMatch(el -> !el.toLowerCase().contains("hello"))){
// toast
}
If you wanna simply check if there is any sting that matches any element of list then do what @SatyendraKumar sugested.
Upvotes: 0
Reputation: 367
If you want to do it one line, do it like this:
if(object.getList().stream().noneMatch(it -> "hello".equalsIgnoreCase(it))){
// ...
}
This will work if you are using Java 8.
Upvotes: 1
Reputation: 5393
I am not really sure how this expression:
Object.getList().toString.trim().toLowerCase().contains("hello")
works. Consider two adjacent elements: "he" and "llo". Even in this case your solution would state that the string "hello" exists in the ArrayList
. Since there is ho hashing in ArrayList
, the only solution is via brute force (Giving a performance of O(n)
). Here is the solution:
for(String element: list) {
if (str.equalsIgnoreCase(element)) {
// Found
}
}
Upvotes: 1