Say I have a string
String s = bob
and the ArrayList
["alex [available]", "bob [away]", "craig [busy]", "david [gone fishing]"]
How would I search the list to get the element at [1]?
Say I have a string
String s = bob
and the ArrayList
["alex [available]", "bob [away]", "craig [busy]", "david [gone fishing]"]
How would I search the list to get the element at [1]?
String strToSearch = yourString + " [";//"bob ["
for (int i = 0; i < list.size(); i++){
if (list.get(i).startsWith(strToSearch)){
neededIndex = i;
break;
}
}
" [" at the end of yourstring to not mix up Jon and Jonathan.You have to iterate the list and do a String.contains("bob") on every item.
for (String item : listOfItems) {
if (item.contains("bob") {
return item;
}
}
Maybe you should extend the search term to bob [ because "bob" might be contained in anoter name.
contains is perhaps too broad. "susan [bobbing for apples]"You probably should be using a Map instead of a List. In this case you need to use a loop.
List<String> nameStatusList = ...
String s = "bob";
FOUND: {
for(String ns: nameStatusList)
if(ns.startsWith(s + " [")) {
System.out.println(ns);
break FOUND;
}
System.out.println("Couldn't find " + s);
}
return ns/return null is an idea.Something like this:
String string = "bob";
private List <String> list = new ArrayList<String>(){{
add("alex [available]");
add("bob [away]");
add("craig [busy]");
add("david [gone fishing]");
}};
public void method(){
String answer;
for (String s : list){
if (s.contains(string)){
answer = s;
break;
}
}
}
for (String str: list) {
if (str.contains(s)) {
return str;
}
}
Replace str.contains(s) with str.matches("^"+s+" [") just in case.
str.matches("^"+s+" [") equivalent to str.startsWith(s+" [")?s = ".*" for example. You need to escape/quote strings before putting them into a regex.