Autocomplete suggestion is a common feature in modern applications that helps users predict possible matches as they type. In this Java program, we implement a simple autocomplete system that filters all strings in an array starting with a given prefix and returns them sorted in lexicographical order.
Problem Statement
Write a Java program to implement a basic autocomplete feature. Given an array of strings and a prefix, please find all the strings that start with the given prefix and return them in lexicographical (alphabetical) order.
Example
Input:
String[] words = {“apple”, “application”, “ape”, “banana”, “appetizer”, “apex”};
String prefix = “app”;
Output:
Suggestions: [appetizer, apple, application]
Approach to Solve the Problem
- Filter Strings: Loop through each string in the array and check if it starts with the given prefix using
.startsWith()
. - Store Matches: Add matching words to a list.
- Sort List: Use
Collections.sort()
to sort the filtered results. - Return or Print: Output the sorted list of suggestions.
Java Program for Autocomplete Suggestions
This Java program implements a basic autocomplete feature by filtering an array of strings to find all elements that start with a given prefix. It uses a loop to check each string with the .startsWith()
method, stores matching results in a list, and then sorts the list alphabetically using Collections.sort()
before displaying the suggestions.
package com.javacodepoint.stringarray;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AutocompleteSuggestions {
// Method to get autocomplete suggestions
public static List<String> getSuggestions(String[] words, String prefix) {
List<String> suggestions = new ArrayList<>();
for (String word : words) {
if (word.startsWith(prefix)) {
suggestions.add(word);
}
}
// Sort the matching suggestions alphabetically
Collections.sort(suggestions);
return suggestions;
}
public static void main(String[] args) {
// Example input
String[] words = { "apple", "application", "ape", "banana", "appetizer", "apex" };
String prefix = "app";
// Get suggestions
List<String> result = getSuggestions(words, prefix);
// Print suggestions
System.out.println("Suggestions: " + result);
}
}
OUTPUT:
Suggestions: [appetizer, apple, application]
Conclusion
This simple program demonstrates how to build a prefix-based search/autocomplete feature using Java. It combines filtering and sorting to deliver results similar to real-world applications like search bars and code editors.
You can learn the Top 20 string array programs for interview preparation (Click here).