Skip to content

How can I loop through a linked list and print each piece of data that matches the input?

I’m working on this method but am running into an issue. When I enter a word that matches the data in an index of the linked list, it only prints the first index of the Linked List the same number of times that the word I entered appears in the entire linked list.

public void iteratePrint(T aData) {
    if (head == null) {
    //Typecast aData to string, and make it lowercase.
    String a = (String)aData;
    String strInput = a.toLowerCase();

    //Create temp listnode to loop through.
    ListNode temp =  head;
    //While temp is not null, check for match and if so, print.
    while(temp != null) {

        //Typecast into string (all of the data is a string anyway) and
        //Make sure it is lowercase.
        String b = (String);
        String strTemp = b.toLowerCase();
        //This checks for the match and prints the current line.
        //Not currently working
        temp =;

For example: The linked list contains these as String data with their respective indices (balls bounce far, dogs play fetch with balls, my favorite toy is a ball). If I enter my input as “ball”, I would like it to print out as

balls bounce far
dogs play fetch with balls
my favorite toy is a ball

However, it only prints out this:

balls bounce far
balls bounce far
balls bounce far

Ball appears 3 times, and it is only printing out the first index of the linked list the amount of times that the input appears.



If strTemp.contains(strInput) is not satisfied temp =; will not get executed hence while loop will get stuck. Take temp =; outside of the if statement.

8 People found this is helpful