How Can TreeSet Be Used to Manage Unique and Sorted State Entries in Java?

  • Comp Sci
  • Thread starter iamjon.smith
  • Start date
  • Tags
    Java Set
In summary, the conversation is about developing an application to read customer information from a file and store the state information in a data structure without duplicates. The states need to be sorted alphabetically. The application will use a CustRecord class to store the first name, last name, street number, street name, street type, city, and state for each customer. The main class uses a scanner to read the input file and loop through each line to set the customer information.
  • #1
iamjon.smith
117
3
You have been tasked to develop an application that reads customer information from a file to determine in which states you have customers.

The file contains records with customer first name, customer last name, street address, city, and state.

The file could contain many customers living in the same state. You need to read all of the records from the file and store only the state information into a data structure without duplicates. The states need to be sorted alphabetically.

Main Class:
Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);

       try{

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())
            { //Checks if there's any more lines

                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                State = scanner.next(); // reads to end of line sets the State

             }

            }

        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        catch (Exception e)
        {
           System.err.println ("Error writing to file");
        }
    }
  }

and my CustRecord Class:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jon and Jessica
 */


public class CustRecord {

   private String custFirst;
   private String custLast;
   private int streetNum;
   private String streetName;
   private String streetType;
   private String City;
   private String State;

   // no-argument constructor calls other constructor with default values
   public CustRecord()
   {
      this(  "", "", 0, "","", "","" ); // call six-argument constructor
   } // end no-argument CityRecord constructor

   // initialize a record
   public CustRecord( String custFirst, String custLast, int streetNum, String streetName, String streetType, String City, String State )
   {
      setCustFirst(  custFirst );
      setCustLast(  custLast );
      setStreetNum( streetNum );
      setStreetName( streetName );
      setCity( City );
      setState( State );
   } // end 6-argument CityRecord constructor

    public String getStreetType() {
        return streetType;
    }

    public void setStreetType(String streetType) {
        this.streetType = streetType;
    }
    public String getCustFirst() {
        return custFirst;
    }

    public void setCustFirst(String custFirst) {
        this.custFirst = custFirst;
    }

    public String getCustLast() {
        return custLast;
    }

    public void setCustLast(String custLast) {
        this.custLast = custLast;
    }

    public String getStreetName() {
        return streetName;
    }

    public void setStreetName(String streetName) {
        this.streetName = streetName;
    }

    public int getStreetNum() {
        return streetNum;
    }

    public void setStreetNum(int streetNum) {
        this.streetNum = streetNum;
    }
   // set city name
   public void setCity( String cityName )
   {
      City = cityName;
   } // end method setCity

   // get city name
   public String getCity()
   {
       return City;
   } // end method getCity

   // set state name
   public void setState( String stateName )
   {
      State = stateName;
   } // end method setState

   // get state name
   public String getState()
   {
       return State;
   } // end method getState

} // end class CityRecord

All I have to do now is to take the state from the CustRecord constructor and place it into a collection. My instructor has STRONGLY recommended using a tree set since it contains no duplicates by default. I also need the states to be sorted alphabetically. There is no requirements as to output so I just intend to output the alphabetized collection to a generic output file (output.txt). I am a little confused as to how to build the collection and get the data from my constructor to the collection.
 
Physics news on Phys.org
  • #2
Ok, I have constructed a new TreeSet, and am using a different input and output stream, so here is the new code for the main class. The supporting CustRecord class remains the same:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;
       FileOutputStream stateOut; // declare a file output object
       PrintStream p1; // declare a print stream object

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);

       try{

             // Create new file output streams
             stateOut = new FileOutputStream("StateList.txt", true); // output stream for states

             // Connect print streams to the output stream
             p1 = new PrintStream( stateOut );

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())//Checks if there's any more lines
            {
                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                State = scanner.next(); // reads to end of line sets the State
             }
             SortedSet StateSet = new TreeSet();
             StateSet.add(State);

             p1.print(StateSet);

             p1.close();

            }

        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        catch (Exception e)
        {
           System.err.println ("Error writing to file");
        }
    }
  }

The problem now is that I am getting an error printing to file when I try to execute.
I will work on debugging it and hope for someone to point me in the right direction
 
  • #3
OK, making more advances. New code as follows:

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;
       FileOutputStream stateOut; // declare a file output object
       PrintStream p1; // declare a print stream object

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);

       try{

             // Create new file output streams
             stateOut = new FileOutputStream("StateList.txt", true); // output stream for states

             // Connect print streams to the output stream
             p1 = new PrintStream( stateOut );

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())//Checks if there's any more lines
            {
                SortedSet StateSet = new TreeSet();

                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                StateSet.add(scanner.next()); // reads to end of line sets the State

                p1.print(StateSet);
             }             p1.close();        }        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        catch (Exception e)
        {
           System.err.println ("Error writing to file");
        }
    }
  }

Ok, now it creates the text file, and writes the states in, but there are duplicates and it is not in alphabetical order. I also still get the error writing to file on the main screen, but it does actually write the file. Here is the output and input:

input file:
Code:
Jonathan Smith 348 Front Circle Piedmont AL
Jessica Smith 431 Left Rd Chatom GA
Charles Stewart 25 South Blvd Paduca KY
Randy Jones 3532 Calioca St Mariannas CA
Otuoka Windtalker 5341 First St FirstTown AK
Jimmy Kimmel 1234 Second St LongBeach CA
Steven Tyler 5432 Wild Rd Mobile AL
James Hetfield 6546 Metallica Blvd Rocking KY

and the output I get:

Code:
[AL][GA][KY][CA][AK][CA][AL][KY]

Any suggestions as to what I am doing wrong with my StateSet collection?
 
  • #4


OK, I don't know what is going on. Here is the code for my main class, custRecord unchanged

Code:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
/**
 *
 * @author Jonathan Smith
 */
public class CustomerRecordTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       Scanner scanner = null;
       FileOutputStream stateOut; // declare a file output object
       PrintStream p1; // declare a print stream object

       String custFirst = "";
       String custLast = "";
       int streetNum = 0;
       String streetName = "";
       String streetType = "";
       String City = "";
       String State = "";

       CustRecord customer = new CustRecord( custFirst, custLast, streetNum, streetName, streetType, City, State);
      
       try{

             // Create new file output streams
             stateOut = new FileOutputStream("StateList.txt", true); // output stream for states

             // Connect print streams to the output stream
             p1 = new PrintStream( stateOut );

             scanner = new Scanner(new File("CustomerRecord.txt")); // Scanner construct that reads the input file

             while (scanner.hasNextLine())//Checks if there's any more lines
            {
                

                TreeSet< String > tree = new TreeSet< String >( Arrays.asList(State));


                custFirst = scanner.next(); // reads to first space in line, sets the First Name
                custLast = scanner.next(); // reads to second space in line, sets the Last Name
                streetNum = scanner.nextInt(); // reads to the next space in line, sets Street Number
                streetName = scanner.next(); // reads to next space sets street Name
                streetType = scanner.next(); // reads to next space sets the street type (rd, circle, blvd, etc.)
                City = scanner.next(); // reads to next space sets the City
                tree.add(scanner.next()); // reads to end of line sets the State and adds the state to the TreeSet
                
                Iterator it1 = tree.iterator();

                while(it1.hasNext()){
                  System.out.println(it1.next());
                }                               
             }
                p1.close();
        }
        catch (Exception e)
        {
           System.err.println("Error Writing To File");
        }
      }
     
  }

Using the same input, here is the output:

output to screen:
Code:
run:

AL

GA

KY

CA

AK

CA

AL

KY
Error Writing To File
BUILD SUCCESSFUL (total time: 3 seconds)

and output to file:
Code:
[, AL][, AL][, GA][, GA][, KY][, KY][, CA][, CA][, AK][, AK][, CA][, CA][, AL][, AL][, KY][, KY]

I need the list to do 2 things:

1. NO DUPLICATES
2. SORT ALPHABETICALLY

It was my understanding, according to my instructor, that a TreeSet cannot contain duplicates, but it is apparent from the output that a TreeSet CAN have duplicates, or I am doing something terribly wrong. Could someone please go over this code and tell me what I am doing wrong?

BTW This assignment is due TONIGHT
 
  • #5
The best I can do is point you to the Java documentation for TreeSet and SortedSet. Just do a Web search for "java TreeSet" or "java SortedSet". I don't have any experience with these types - sorry. And Grep doesn't seem to be around.
 
  • #6
Mark44 said:
The best I can do is point you to the Java documentation for TreeSet and SortedSet. Just do a Web search for "java TreeSet" or "java SortedSet". I don't have any experience with these types - sorry. And Grep doesn't seem to be around.

Problem solved, thanks for the offer though. I toughed it out, and kind of posted questions to the board as I worked my way through the program. I actually figured it out by "Talking to the forum" LOL.
 

1. What is a Tree Set in Java Collections?

A Tree Set in Java Collections is a type of data structure that stores elements in a sorted order. It is implemented using a binary tree data structure, which allows for efficient insertion, deletion, and retrieval of elements. In a Tree Set, elements are stored in a sorted order based on their natural ordering or a custom comparator.

2. How is a Tree Set different from other Java Collections?

A Tree Set is different from other Java Collections in that it maintains a sorted order of elements. This means that when elements are added to the Tree Set, they are automatically sorted in their natural ordering or according to a custom comparator. Other Java Collections, such as ArrayList or HashSet, do not guarantee a specific ordering of elements.

3. What is the time complexity of operations in a Tree Set?

The time complexity of operations in a Tree Set is O(log n), where n is the number of elements in the set. This is because a Tree Set uses a binary tree data structure, which allows for efficient insertion, deletion, and retrieval of elements. However, in the worst case, the time complexity can be O(n) if the tree becomes unbalanced.

4. Can a Tree Set contain duplicate elements?

No, a Tree Set cannot contain duplicate elements. As mentioned earlier, elements in a Tree Set are stored in a sorted order, and duplicate elements are not allowed. If an attempt is made to add a duplicate element to a Tree Set, it will simply be ignored and not added to the set.

5. When should I use a Tree Set?

A Tree Set is useful when you need to store elements in a sorted order and perform operations such as insertion, deletion, and retrieval efficiently. It is also a good choice when you want to maintain a unique set of elements and do not want to allow duplicates. However, if you do not need to maintain a specific order or uniqueness, other Java Collections such as ArrayList or HashSet may be more suitable.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
31
Views
11K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
3K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
21
Views
5K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
3K
Back
Top