Reputation: 101
final HashSet<String> VALUES = new HashSet<String>(Arrays.asList(new String[] {"OK (0.07, 0.05, 0.01)",
"OK (0.07, 0.05, 0.02)",
"OK (0.07, 0.05, 0.03)",
"OK (0.07, 0.05, 0.04)"}));
String s="OK";
System.out.println(VALUES.contains(s));
Gives me false. How do I check if "OK" exists in each of the elements?
Upvotes: 2
Views: 7732
Reputation: 32
you can test this code:
final HashSet<String> VALUES = new HashSet<String>(Arrays.asList(new String[] {"OK (0.07, 0.05, 0.01)",
"OK (0.07, 0.05, 0.02)",
"OK (0.07, 0.05, 0.03)",
"no (0.07, 0.05, 0.04)"}));
String s="OK";
@Test
public void teste(){
for (String a : VALUES) {
if(a.contains(s)){
System.out.println("Ok yes!" + true);
}else{
System.out.println("Don't exist!" + false);
}
}
}
Upvotes: 2
Reputation: 3914
boolean contains = true;
String s = "OK";
for (String str : VALUES) {
if (!str.conatins(s)) {
contains = false;
break;
}
}
// If contains is true here, every string in the list contains s, otherwise not.
Upvotes: 2
Reputation: 93872
Currently, you're checking if your Set
contains the value OK
. If you want to check if each of the elements of the Set
contains OK
(note the difference), you'll need to loop through the values of your Set
like the others stated.
Using java-8 and streams, you can also do :
boolean b = VALUES.stream().allMatch(s -> s.contains("OK"));
Upvotes: 9
Reputation: 201467
You could write a method like contains
below to loop over the elements in the Collection
.
public static boolean contains(java.util.Collection<String> coll, String s) {
for (String t : coll) {
if (t == null) {
continue;
}
if (!t.contains(s)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
final HashSet<String> VALUES = new HashSet<String>(Arrays.asList(new String[] {"OK (0.07, 0.05, 0.01)",
"OK (0.07, 0.05, 0.02)",
"OK (0.07, 0.05, 0.03)",
"OK (0.07, 0.05, 0.04)"}));
System.out.println(contains(VALUES, "OK"));
}
Which outputs true
here.
Upvotes: 1
Reputation: 95978
You should loop on the set and check for every string in it:
for(String st : VALUES) {
if(!st.contains(s)) {
//found string that doesn't contain s
}
}
Note that now we are using String#contains
.
Upvotes: 4