0

I have a String[] with some tags.

In my example: image.getRepoTags[0] = clone_envx:img1 and imageTag = img1

My code returns false. Why ? How to do check if imageTag is in String[] image.getRepoTags()?

 if(Arrays.asList(image.getRepoTags()).contains(imageTag))
       return true;
  else
       return false;
5
  • 8
    there is a difference between list.contains() and string.contains(). that is your problem here. the first checks if there are exact matches of the whole object, while the second checks for the actual content of the strings Commented Feb 8, 2018 at 12:01
  • @XtremeBaumer can you give me an example how would I fix this? Commented Feb 8, 2018 at 12:07
  • If imageTag = " clone_envx" It must return true? and It 's "tag1:tag2:tag3:img1" a valid value of getRepoTags()[0] ? Commented Feb 8, 2018 at 12:11
  • made a java 7 solution. although we have some valid java 8 versions too Commented Feb 8, 2018 at 12:11
  • If imageTag = " img" It must return true? Commented Feb 8, 2018 at 12:12

3 Answers 3

2

There is a difference between list.contains() and string.contains(). That is your problem here. The first checks if there are exact matches of the whole object, while the second checks for the actual content of the strings.

Example for list.contains():

new String[]{"test", "test2", "img1"}

contains the actual string object img1 (true). If we change the array to

new String[]{"test", "test2", "clone_envx:img1"}

then it doesn't contain a perfect match (false).

Java 7 solution to the problem:

for (String str : image.getRepoTags()) {
    if(str.contains(imageTag)) {
        return true;
    }
}
return false;

the second return should only happen after iterating the whole list. That is the reason it is after the loop.

Sign up to request clarification or add additional context in comments.

Comments

2

Converting the array into List will not help you to address your need as you want to search inside the String elements.

You could iterate the array elements and stop as soon as one element contains imageTag:

return  Arrays.stream(arr)
              .anyMatch(s -> s.contains("imageTag"));

2 Comments

IMHO it's better: return Arrays.stream(image.getRepoTags()) .anyMatch(s -> s.contains(imageTag));
@ David Pérez Cabrera Much simpler indeed. Thanks a lot !
0

You should loop or stream the list of tags and check if any of them contains your imageTag variable.

For example in Java 8:

    boolean anyMatch = Arrays.asList(image.getRepoTags()).stream()
                            .anyMatch(tag -> tag.contains("img1"));

1 Comment

you can directly return the value return Arrays.asList(image.getRepoTags()).stream().anyMatch(tag -> tag.contains(imageTag)) ? true : false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.