문제

    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?

도움이 되었습니까?

해결책 3

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

        }

다른 팁

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

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.

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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top