I need idea to create search text in list

Hi Experts,

I am have one HasMap, which contain ID as key and name as value.

In that Map i need to find out name which starts with 's' character.

Example: 00001, Satya Sunil

00002, Munna Prasad. This is input in HashMap. Just i gave 2 rows for example.

If i need to search starts with 's' in Map, How to write a code with less time complexcity (with out using any for loop, because i have thousands recodes in MAP).

Or tell any idea to do this and where to store to get fast the names other than using MAP.

Regards,

Sunil.

[584 byte] By [satyasunil_java@yahoo.co.ina] at [2007-11-27 11:42:21]
# 1

the good things about maps is that they use constant time in order to get a particular value for a key..

The only way i can think of to get all of the entries beginning with an "s" would be to use a loop which you said you dont want to do.

Another suggestion would be to change the way you store things in the map..

rather than store the names as separate entries in the map, have a map that stores an ArrayList relating to each character in the alphabet, and within each arrayList you would store the list of names.. let me show some example code incase I am being unclear..

HashMap< Character, ArrayList< String > > map = new HashMap< Character, ArrayList< String >> ();

// initialize all of the arrayLists like so.

char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();

for( char letter: alphabet )

{

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

map.put( (Character)letter , dataList );

}

/* Now that all of the lists that will contain the information in the map have been initialized, you can add names like this..

*/

private void addName( String name )

{

// Determine the first letter of the name

Character startingLetter = (Character)name.charAt( 0 );

// get the arrayList in the map that is storing all of the names begging with that letter

ArrayList< String > list = map.get( startingLetter );

//put the name in the list.

list.add( name );

}

/* Now when you want to retrieve all of the names with "s" lets say,

*/

ArrayList< String > sNames = map.get( (Character)s );

// then you can iterate through the list of sNames in whatever fashion.

Hope this helps.

smithdale87a at 2007-7-29 17:43:39 > top of Java-index,Core,Core APIs...