aamadmi
aamadmi

Reputation: 2730

What DS to use for search a string in set of strings in Java?

I have a few strings(about 100) and I want to store them in a Data Structure and then later I want to search it for a particular string to check whether its present or not. What DS in Java will be best in this case for fast searching.

The actual use case is that I want to create a catalog for books and need to find out whether a particular title is present or not.

All the strings are unique. I dont want to implement any DS myself but want to use any of the Collections already present in Java.

Upvotes: 1

Views: 233

Answers (3)

kgiannakakis
kgiannakakis

Reputation: 104188

The obvious choice would be to use an implementation of the Set interface. This exposes a convenient contains method, which you can use to test if a specific title exists. You could also use an implementation of a Map, like HashMap to associate a String with an object. This will allow you to store information about your book and easily access it.

The advantage of using a Set or a Map, is that searching for a specific key is very effective. You can't have duplicate items in a Set.

Upvotes: 3

Chandra Sekhar
Chandra Sekhar

Reputation: 19502

why don't you use any List to store all the strings and use contains() method to find whether it present in your List or not.

You can even use Set but in that case your strings must be unique.

Upvotes: 2

darrengorman
darrengorman

Reputation: 13114

Use a Set implementation. The contains method will tell you if a particular String title is present or not

Upvotes: 1

Related Questions