Search for value and keep going

Viewed 61

I have a program that has a list of items.

I then search for a string and try to find it in said list.

What I would want to happen is: It finds the first occurrence, then prints it out or saves it somewhere so I can use it later (by highlighting user choice for example). Then once I search for the same string again it should return me the second occurrence, then the third, etc. When it doesn't find any more occurrences it should go back to the start and repeat it.

This is a crude example of what I have:

public static void main(String[] args) {

        ArrayList<String> exampleList = new ArrayList<String>();

        exampleList.add("string1");
        exampleList.add("john");
        exampleList.add("string2");
        exampleList.add("arnold");
        exampleList.add("string3");

        String inputExample = "str"

        for (String s : exampleList) {

            if (s.contains(inputExample)) {

                System.out.println(s);
                break;
            }

        }

    }

I added the break inside the if so I can get only the first result. If I remove it I will get all results.

In the program I have similar code associated to the click of a button, highlighting the user choice if the list contains what the user searched for, this is just an example.

What happens in my program is that only the first result will be highlighted (because I broke out of the loop) or only the last result will be highlighted (because I didn't break out of the loop).

How can I make it so the search picks up where it left off, officially ignoring the results it already obtained?

3 Answers

You can loop through your list and each time you find the string you can call your method to highlight it. Alternatively, if you want to be able to get strings 1 by 1 each time you call your method, then you can use an iterator. On the first call to your method you obtain an iterator for your list and store it in a private field of your class. On subsequent calls you use this iterator to get the next matching string from your list.

As @Alex pointed out in his answer you should use an iterator and save your results in a private ArrayList for furthure use of those search results.

If you are not familiar with the iterator use this

I have written a simple class HighlightingUserInput that behaves as your conditions. It gives the first search result and prints it and saves in a ArrayList, if you didn't exit the program(or you can add a search button, if user presses search again) then gives the second search result, etc.

Feel free to ask anything related to this following program.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

public class HighlightingUserInput{

   private static ArrayList<String> resultsString=new ArrayList<>();

   public static void main(String [] args) {

      ArrayList<String > allStrings=new ArrayList<>();

      allStrings.add("string1");
      allStrings.add("john");
      allStrings.add("string2");
      allStrings.add("arnold");
      allStrings.add("string3");

      Scanner scanner=new Scanner(System.in);

      CharSequence userIput=scanner.nextLine();

      Iterator iterator = allStrings.iterator();

      while(!scanner.nextLine().equals("exit")) {

         inner:
         while (iterator.hasNext()) {
            String s = (String) iterator.next();
            if (s.contains(userIput)) {
                System.out.println(s);
                HighlightingUserInput.resultsString.add(s);
                break inner;
            }

         }

         if(!iterator.hasNext())
             iterator = allStrings.iterator();


       }
   }

}
public static void main(String[] args) {

    ArrayList<String> exampleList = new ArrayList<String>();

    exampleList.add("string1");
    exampleList.add("john");
    exampleList.add("string2");
    exampleList.add("arnold");
    exampleList.add("string3");

    String inputExample = "str";
    int count = 0;
    while(count >= 0){
        System.out.println(customSearch(exampleList, inputExample, count);
        count ++;
        } // write break statement when count reaches to a particular value based on your use case

String customSearch(List<String> words, String searchKey, int count){
    List<String> searchedWords = words.stream().filter(word -> if word.toLowerCase().contains(searchKey.toLowerCase)).collect(Collectors.toList());
    return searchWords.get(count%searchedWords.size());
Related