2
 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?

4
  • 2
    Loop the Set and check if the String in the Set contains "OK". Commented Jan 3, 2014 at 17:24
  • I'am afraid you have to loop ... Commented Jan 3, 2014 at 17:24
  • Tangential note, you don't need the new String[] { or the closing }. Just Arrays.asList("OK (0.07, 0.05, 0.01)", ... ). asList takes a varargs String.... Commented Jan 3, 2014 at 17:27
  • you need to check every entry in this map by a loop Commented Jan 3, 2014 at 17:32

5 Answers 5

9

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 and streams, you can also do :

boolean b = VALUES.stream().allMatch(s -> s.contains("OK")); 
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

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); } } } 

Comments

2
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. 

1 Comment

You can break the loop, in your if statement, no need to check the other values, you already found one that did'nt satisfied the condition.
1

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.

1 Comment

Didn't he want contains? You are using startsWith.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.