public List<Topic> findExistingTopicsByPrefix(String prefix) {
        ListTopicsResult listTopicsResult = admin.listTopics();
        try {
            String fullPrefix = COMMON_TOPIC_PREFIX + prefix;

            // Get all topic listings
            Map<String, TopicListing> topicListingsMap = listTopicsResult.namesToListings().get();

            // Filter topic names by prefix
            List<String> matchingTopicNames = topicListingsMap.keySet().stream()
                    .filter(name -> name.startsWith(fullPrefix)) // Corrected fulalPrefix to fullPrefix
                    .collect(Collectors.toList());

            if (matchingTopicNames.isEmpty()) {
                return Collections.emptyList();
            }

            // Describe the filtered topics to get partition info
            DescribeTopicsResult describeTopicsResult = admin.describeTopics(matchingTopicNames);
            Map<String, TopicDescription> topicDescriptions = describeTopicsResult.allTopicNames().get();

            return matchingTopicNames.stream()
                    .map(name -> {
                        TopicDescription description = topicDescriptions.get(name);
                        if (description != null) {
                            int partitionCount = description.partitions().size();
                            return new Topic(name, partitionCount);
                        } else {
                            // This case should ideally not be reached if a topic name from listTopics is
                            // passed to describeTopics
                            // and the topic still exists.
                            LOGGER.warn("Could not find description for topic: {}. It might have been deleted.", name);
                            return null;
                        }
                    })
                    .filter(Objects::nonNull) // Filter out any nulls if a description was missing
                    .collect(Collectors.toList());

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // It's good practice to specify which operation was interrupted.
            throw new RuntimeException("Interrupted while listing or describing topics", e);
        } catch (ExecutionException e) {
            // Similarly, specify the operation.
            throw new RuntimeException("Failed to list or describe topics", e);
        }
    }
Find existing topics with the given prefix.
tools/src/main/java/org/apache/kafka/tools/automq/perf/TopicService.java