Java: How to check if a string is a part of any LinkedList element?

11,402

Solution 1

String a = "apple";
String listelement = "a bunch of apples";
List<String> list = new LinkedList<String>();
list.add(listelement);
for(String s : list){
  if(s.contains(a)){
   syso("yes");
  }
}

This should do it, in order to find a node contains a particular string, you need to iterate through all the nodes. You can break the loop, if you want only 1 instance.

Also you want to use Generics. Look at the code. otherwise you will have to cast the node to a String.

Solution 2

String a = "apple";
    String listelement = "a bunch of apples";
    LinkedList<String> list = new LinkedList<String>();
    list.add(listelement);
    Iterator<String> li = list.iterator();
    while (li.hasNext()) {
        if (li.next().contains(a)) {
            System.out.println("Hooray!");
        } 
    }
Share:
11,402
Blackvein
Author by

Blackvein

Updated on June 20, 2022

Comments

  • Blackvein
    Blackvein almost 2 years

    Okay so I have a LinkedList, and I have a String. I want to check if the String is contained within any of the LinkedList elements. For example:

    String a = "apple";
    String listelement = "a bunch of apples";
    LinkedList list = new LinkedList();
    list.add(listelement);
    if(list.containsany(a){
       System.out.println("Hooray!");
    }
    

    Would result in printing "Hooray!"

    Obviously list.containsany isn't a real LinkedList method, I'm just using it for this purpose.

    So how can I simulate my example?

    Thanks

  • DarthVader
    DarthVader over 12 years
    contains do full match of the node. not partial match of a string.
  • Visionary Software Solutions
    Visionary Software Solutions over 12 years
    Does this work if the linked list has Strings and Objects in it?
  • DarthVader
    DarthVader over 12 years
    this one works only for string. if you are using object, you need to cast it. and you cant store an object to a LinkedList<String>
  • Visionary Software Solutions
    Visionary Software Solutions over 12 years
    Correct, now that you've added generics to the type of the list. :)
  • Blackvein
    Blackvein over 12 years
    This is perfect! One question though, the "for" statement does not perform the "else" if the LinkedList contains no elements. Is this something that I can fix?
  • Visionary Software Solutions
    Visionary Software Solutions over 12 years
    Sure, just surround it in an if statement that checks if the size of the list is 0, and in that case print out something appropriate. (If you need help with this, Javadocs are your friend)