Hello,

I am new to programming and I have to write a program to perform a fast search on address book. The address book records are in csv file and contains 4 fields - first name, last name, phone number and company name. My problems are -
1. How do I connect the data on csv to the java program, means how do I import the address book, keeping all the fields in csv file linked to each other?
2. What data structure shall I use in java which is appropriate for an address book program?
3. I do not need to give any functionality to create a new record in address book, but I have to give a search functionality on all 4 fields. This would mean I have to have to keep the data sorted. How can I keep data sorted on all 4 fields? Or if I keep it sorted on 1 field only, which field shall I choose? How do I sort the data?

I don't even know how to begin. Can anybody show me some sample programs which does all this? Any help would be highly appreciated!

Thank you!

Dani AI

Generated

A concise, practical plan to make this work and fix the bugs you’re seeing. Read the CSV into a small Contact POJO (first/last/phone/company) using a proper CSV parser (or BufferedReader if the file is simple). Store both the original strings and a precomputed normalized form (trimmed + toLowerCase(Locale.ROOT)) inside each Contact so comparisons are fast and consistent. ’s idea to use a custom data type is correct; prefer using Comparators (not only Comparable) so you can sort on different fields without changing the class.

Your uppercase/lowercase bug comes from normalizing incorrectly and combining methods that don’t belong together. Normalize the search term once and compare against pre-normalized fields. Example pattern:

String q = query.trim().toLowerCase(Locale.ROOT);
if (contact.firstNameLower.startsWith(q)) {
    // match
}

Binary-search notes and a simple way to demonstrate it. Collections.binarySearch only works on a list sorted with the same key/comparator you use for searching, and it finds an index for an exact compare result. To show binary-search performance on a prefix search, sort the list by the search field, use Collections.binarySearch with a Comparator for that field to locate any match, then expand left/right to find the full range of prefix matches. Example approach:

Collections.sort(list, Comparator.comparing(c -> c.firstNameLower));
int idx = Collections.binarySearch(list, new ContactForKey(q), Comparator.comparing(c -> c.firstNameLower));
if (idx >= 0) {
  int lo = idx, hi = idx;
  while (lo > 0 && list.get(lo-1).firstNameLower.startsWith(q)) lo--;
  while (hi+1 < list.size() && list.get(hi+1).firstNameLower.startsWith(q)) hi++;
  int matches = hi - lo + 1;
}

Performance/design choices. If your address book is small (<10k) a linear scan with normalized fields is simplest and fast enough. For much larger data, build per-field indexes: TreeMap for prefix ranges (use subMap), HashMap for exact matches, or a Trie for very fast prefix lookups. Use System.nanoTime() to time only the search step (not the CSV parsing) when demonstrating timings. Finally, avoid naive String.split(",") on real CSVs—use a CSV parser to handle quoted commas correctly.

Recommended Answers

All 4 Replies

You should start and we will help you.
and about your questions:
1- I don't know how can we import this special file type (csv) and use its facilities but in general you can read the file by using FileInputStream class.

2- I think it is better to creat your own data structure containing the attributes first name, last name, phone number and company name and all their types are suitable to be string.

3-In order to sort the data your class should implement compareable interface and override compareTo method and define the style to compare your class instances.
then you can add your data to an array and use the class method

Arrays.sort(yourClassInstanceArray)

You just start your job and we will help you.
Good luck

With some google I found these
and this site which helps.

Thank you so much for your encouraging words and help..as you advised, I'll start working on it and come back here for help!

Thank you again,
Priya

Hi again,

I have written this program but I have a few problems with it-
1. It is not returning me any result when searched on capital letter. For example, if I search on "a" it will list matches found, but when searching on "A" it says 0 matches found. I have tried IgnoreCase, toLowerCase, but probably I am not doing it right.
2. I have to demonstrate binary search algorithm with this program, along with display of time taken to find result, how do I do it?

 public void getResultsByFirstName(String pFirstName) throws IOException{
     long inTime;
     long totalTime;
     inTime = System.currentTimeMillis();
     ArrayList<String> records = new ArrayList<String>();
       String searchStr = null;
       String[] splitStr = null;
       searchStr = toLowerCase().pFirstName;
        for(int i=0; i <csvData.size();i++){
        splitStr = csvData.get(i).split(",");

        if(splitStr[0].equalsIgnoreCase().startsWith(searchStr)){
            records.add(csvData.get(i));
        }
        }
        System.out.println("Results: \n");
         for(int x=0; x < records.size();x++){
        System.out.println(records.get(x));
         }
        Collections.sort(records);
        int count = Collections.binarySearch(records, searchStr);
        int totalCount = count + (-2)*count -1;
        System.out.println("("+totalCount+ " total matches)");
        totalTime = System.currentTimeMillis() - inTime;
        System.out.println("Results fetched in: " +totalTime+ "ms");
        anotherSearchValidation();
      }

Would be thankful to anyone who can help me..

Regards,
Priya

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.