monty_bean
monty_bean

Reputation: 514

Java/Groovy How do I correctly compare two string values? .equals() not working

Ok, this is driving me nuts. I'm not too savvy with Java/Groovy but please point me to the right direction!

I have a GET call with response text like "["a","b","c"]"

I finally got it to arraylist to iterate through to compare strings. I tried .equals(), .equalsIgnoreCase(), compareTo(), Objects.equals() etc. It does not match. I get "String not the same". What am I missing?

def sb= new StringBuffer();
def rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

def line;
while((line=rd.readLine()) !=null) {
    sb.append(line);
}

//sb = "["a","b","c"]"

List<String> tempList = new ArrayList<String>(Arrays.asList(sb.replaceAll("\\[|\\]","").split(",")));
int count = 0;
String strToFind= "a";

for (String iT : tempList){
    if (strToFind.equals(iT)){
        log.debug("\nString the same\n");
    } else {
        log.debug("\nString not the same\n");
    }
}

Upvotes: 1

Views: 570

Answers (1)

Michael Michailidis
Michael Michailidis

Reputation: 1052

That happens because the String you try to match has quotes.. so you are doing a == "a" which is not the same.. if you don't want to use your debugger to validate what I said try to compare their lengths ( or print them ). the answer applies for this String sb = "["a","b","c"]" which was feeded to the InputStreamReader the same way you provided it.

BufferedReader rd = new BufferedReader(new InputStreamReader(new ByteArrayInputStream("[\"a\",\"b\",\"c\"]".getBytes())));

Upvotes: 4

Related Questions