2757

I have a String[] with values like so:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"}; 

Given String s, is there a good way of testing whether VALUES contains s?

7
  • 8
    Long way around it, but you can use a for loop: "for (String s : VALUES) if (s.equals("MYVALUE")) return true; Commented Jul 15, 2009 at 0:51
  • 3
    @camickr--I have a nearly identical situation with this one: stackoverflow.com/a/223929/12943 It just keeps getting votes yet was just a copy/paste from sun's documentation. I guess score is based on how much help you provided and not how much effort you put into it--and mostly how fast you post it! Maybe we've stumbled onto John Skeet's secret! Well good answer, +1 for you. Commented Apr 29, 2013 at 6:50
  • 3
    If you're using Apache Commons, then org.apache.commons.lang.ArrayUtils.contains() does this for you. Commented Nov 12, 2013 at 21:05
  • 52
    @camickr because people, like me, google a question, click on the SO result, see your answer, test it, it works, upvote the answer and then leave. Commented Jul 20, 2015 at 2:41
  • 3
    I really miss a simple indexOf and contains in java.util.Arrays - which would both contain straightforward loops. Yes, you can write those in 1 minute; but I still went over to StackOverflow expecting to find them somewhere in the JDK. Commented May 1, 2020 at 10:38

33 Answers 33

1
2
0

Arrays.stream(VALUES).anyMatch(value -> StringUtils.equalsIgnoreCase("s", value));

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

Comments

0

You can implement a simple search along with a status value.

Here String s is your search value. I have hardcoded here but you can take it as a user input also.

String[] VALUES = new String[] {"AB","BC","CD","AE"}; String s="ABC"; boolean status =false; for(int i=0;i<VALUES.length;i++) { if(VALUES[i].equals(s)) { System.out.println("Element Found"); status=true; break; } } if(status==false) System.out.println("Element Not Found"); } 

Comments

-2

You can check it by two methods

A) By converting the array into string and then check the required string by .contains method

String a = Arrays.toString(VALUES); System.out.println(a.contains("AB")); System.out.println(a.contains("BC")); System.out.println(a.contains("CD")); System.out.println(a.contains("AE")); 

B) This is a more efficent method

Scanner s = new Scanner(System.in); String u = s.next(); boolean d = true; for (int i = 0; i < VAL.length; i++) { if (VAL[i].equals(u) == d) System.out.println(VAL[i] + " " + u + VAL[i].equals(u)); } 

1 Comment

The string conversion is absurdly inefficient and the solution is incorrect, e.g. contains(",") will return true.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.