Reputation: 410
I have a weird problem that I am trying to solve,
I have a enum with a string something like this
public enum Enumm{
Item1("i1"),
Item2("i2");
private String itemText;
private Enumm(String inText){
this.setitemText(inText);
}
// getter and setter for itemText not typing
}
now in the other class I want to check if a string inputString contains either "i1" or "i2" but the problem is I cannot use a loop.
I know I can do this
for(Enumm item: Enumm.values()){
if (inputString.contains(item.getItemText)) {
// do something
}
}
but the constraints of my problem do not allow me to do it this way
I am looking for something like
if(inputString.contains(Enumm.Item1.getItemText||Enumm.Item2.getItemText)){
//do something
}
but is also dynamic such that it finds all the items in the enum could anyone help me find a solution ?? Thanks in advance.
Upvotes: 0
Views: 98
Reputation: 11
Maybe this could help?
List<String> list = Collections.list(enumeration);
boolean b = list.contains("Searchstring");
Upvotes: 1
Reputation: 3912
You could add a static method to your enum called something like findInString(String s)
that does the loops over the values()
for you and returns a boolean if it finds it. But it depends on why you are trying to avoid the loop. Obviously, this does nothing except squirrels the loop away where you can't see it.
Upvotes: 1
Reputation: 220
You can make an Item list/array and then parse through the array to check for i1 or i2.
Item[] string = {"i1","i2"}
if(string.contains("i1")||string.contains("i2"))
{
}
Upvotes: 1