0

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]?

1
  • you want to get "bob" only? Commented Dec 3, 2012 at 10:47

5 Answers 5

6
String strToSearch = yourString + " [";//"bob ["

for (int i = 0; i < list.size(); i++){
    if (list.get(i).startsWith(strToSearch)){
         neededIndex = i;
         break;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1. But maybe add a " [" at the end of yourstring to not mix up Jon and Jonathan.
2

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.

2 Comments

+1 for the enhanced for loop, and the return instead of ugly break, but OP probably wants a prefix match (did not say so, though).
contains is perhaps too broad. "susan [bobbing for apples]"
1

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);
}

4 Comments

@user714965 So it can handle the "not found" condition without additional checks.
Maybe an extra method and a return ns/return null is an idea.
@Thilo three people also suggested this ;) so I wanted to provide an alternative.
@PeterLawrey: Re: alternative. You did mention using a better datastructure, too ;-)
0

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;
        }
    }
}

Comments

0
for (String str: list) {
   if (str.contains(s)) {
      return str;
   }
}

Replace str.contains(s) with str.matches("^"+s+" [") just in case.

3 Comments

Regex injection vulnerability!
@Thilo You're right, we should avoid regex. But in this case isn't str.matches("^"+s+" [") equivalent to str.startsWith(s+" [")?
Not if s = ".*" for example. You need to escape/quote strings before putting them into a regex.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.