Printing out HashMap sorted
Hi All ,
trying to sort a HashMap then print it to a file.
I have data like in a csv file:
Full Name,Email,Phone,Street Address,City,State,Zip
James Madison,jmadison@whitehouse.gov,201-555-1234,12 Main Street,Newark,NJ,11346
theodore roosevelt, teddy@whitehouse.gov, 415-555-1234, 1239 Geary, San Francisco, CA,95412
I am splitting the full name into two with StringTokenizer, then placing
the ln a map as a key and the entire line into a hashmap lke:
public class NewerSorter {
public NewerSorter(){
}
private static String fname = "";
private static String lname = "";
private static String fullname = "";
private static String email = "";
private static String phone = "";
private static String streetaddress = "";
private static String city = "";
private static String state = "";
private static String zip = "";
private static int numberOfRows = 0;
private static int numberOfColumns = 0;
public static int getNumberOfRows(){
return numberOfRows;
}
public static int getNumberOfColumns(){
return numberOfColumns;
}
public static void setNumberOfRows(int rows){
numberOfRows = rows;
}
public static void setNumberOfColumns(int rows){
numberOfColumns = rows;
}
public static void accessFile(){
Map map = new HashMap();
try{
PrintWriter out = null;
BufferedReader in = new BufferedReader(new FileReader("/Users/Admin/Desktop/list.csv"));
String line;
while ((line = in.readLine()) != null) {
// System.out.println(line);
StringTokenizer st = new StringTokenizer(line, ",");
numberOfColumns= st.countTokens();
while (st.hasMoreTokens()){
//System.out.println(st.nextToken());
fullname = st.nextToken();
StringTokenizer wsp = new StringTokenizer(fullname, " ");
while(wsp.hasMoreTokens()){
fname = wsp.nextToken();
lname = wsp.nextToken();
}
email = st.nextToken();
phone = st.nextToken();
streetaddress = st.nextToken();
city = st.nextToken();
state = st.nextToken();
zip = st.nextToken();
//System.out.println(line);
//System.out.println(fname + lname + email + phone + streetaddress + city + state + zip);
//System.out.println(line);
map.put(lname.CASE_INSENSITIVE_ORDER, line);
//BufferedWriter out = new BufferedWriter(new FileWriter("name-sort.csv"));
//out = new PrintWriter(new BufferedWriter(new FileWriter("name-sort.csv")));
//out.println(sorted);
//System.out.println(sorted);
}
out.flush();
out.close();
}
in.close();
}catch (FileNotFoundException fnfe)
{System.out.println("File not found");}
catch(IOException ioe){
System.out.println("There was a problem reading the file");
}
}
public static void main(String[] args) throws Exception {
accessFile();
int rows = getNumberOfRows();
int columns = getNumberOfColumns();
}
}
I cant get the map sorted , nor written to a file. When I write to a file, only the first line gets written.
Help!
[3275 byte] By [
iketurnaa] at [2007-11-27 6:24:05]

# 1
Well this code doesn't sort the HashMap at all, or write to a file either, but to do (a) all you need is a TreeMap instead of a HashMap, with an appropriate Comparator, and to do (b) you have to write some code.
ejpa at 2007-7-12 17:42:33 >

# 2
I understand that. I have trouble with the comparator part mostly.I ve been looking at code for days, but cant figure out!Any help is appreciated.M
# 3
What code? All you have to do is call Collections.sort() with a Comparator that orders your objects correctly. What have you come up with so far?
ejpa at 2007-7-12 17:42:33 >

# 4
That is it.I don't quite understand how Comparator is suppossed to be used?Also, Should I just use a treemap instead of a hashmap, then:Collections.sort(treemap);or do I have to cast my treemap to a list?I am lost!
# 5
Map<YourObject, Object> map =
new TreeMap<YourObject, Object>(new Comparator<YourObject>(){
public int compare(YourObject o1, YourObject o2) {
// your logic here
}
});
http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
# 6
Sorry,but Im not use to thie notation:<YourObject, Object>
# 7
Map map = new TreeMap(new Comparator(){
public int compare(Object o1, Object o2) {
// cast the Objects to whatever type your keys are
// ...
// your logic here
}
});
# 8
I have to say, I am a baby when it come to collections.I see you are trying to lead me, but I cant get it.
# 9
> I have to say, I am a baby when it come to collections.> I see you are trying to lead me, but I cant get it.Try reading the tutorial I posted in reply #5.
# 10
Ok, So I used the tutorial, here is what I have:
Contact.java
package mybeans;
import java.util.*;
public class Contact implements Comparable<Contact>{
private final String fname, lname, email, phone, address, city, state, zip;
public Contact(String fname, String lname, String email, String phone, String address, String city, String state, String zip) {
if(fname == null || lname==null)
throw new NullPointerException();
this.fname = fname;
this.lname = lname;
this.email = email;
this.phone = phone;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
}
public String fName() {return fname;}
public String lName() {return lname;}
public String email() {return email;}
public String phone() {return phone;}
public String address() {return address;}
public String city() {return city;}
public String state() {return state;}
public String zip() {return zip;}
public boolean equals(Object o) {
if(!(o instanceof Contact))
return false;
Contact c = (Contact)o;
return c.fname.equals(fname) &&
c.lname.equals(lname) && c.email.equals(email) && c.phone.equals(phone) && c.address.equals(address) && c.city.equals(city) && c.state.equals(state) && c.zip.equals(zip);
}
public int hashCode() {
return 31*fname.hashCode() + lname.hashCode() + email.hashCode() + phone.hashCode() + address.hashCode() + city.hashCode() + state.hashCode() + zip.hashCode();
}
public String toString() {
return fname + "" + lname + email + phone + address + city + state + zip;
}
public int compareTo(Contact c) {
int lastCmp = lname.compareTo(c.lname);
return(lastCmp != 0 ? lastCmp:
fname.compareTo(c.fname));
}
}
ContactSort.java
I am using this now to test:
import java.util.*;
public class ContactSort {
public static void main(String[] args) {
Contact contactArray[] = {
new Contact("John", "Lennon"),
new Contact("Karl", "Marx"),
new Contact("Groucho", "Marx"),
new Contact("Oscar", "Grouch")
};
List<Contact> contact = Arrays.asList(contactArray);
Collections.sort(contacts);
System.out.println(contacts);
}
}
Im trying to now read my data from a csv file like so:
public static ArrayList accessFile(){
final Map map = new HashMap();
try{
PrintWriter out = null;
BufferedReader in = new BufferedReader(new FileReader("/Users/custodian/Desktop/list.csv"));
String line;
//Start reading the file while
while ((line = in.readLine()) != null) {
// System.out.println(line);
StringTokenizer st = new StringTokenizer(line, ",");
//This gets us the number of columns:
//Counting tokens while
while (st.hasMoreTokens()){
//System.out.println(st.nextToken());
String fullname = st.nextToken();
StringTokenizer wsp = new StringTokenizer(fullname, " ");
//breaking full name apart while
while(wsp.hasMoreTokens()){
String fname = wsp.nextToken();
String lname = wsp.nextToken();
}
String email = st.nextToken();
String phone = st.nextToken();
String streetaddress = st.nextToken();
String city = st.nextToken();
String state = st.nextToken();
String zip = st.nextToken();
}
// out.flush();
//out.close();
}
in.close();
}catch (FileNotFoundException fnfe)
{System.out.println("File not found");}
catch(IOException ioe){
System.out.println("There was a problem reading the file");
}
}
not sure how to load into the namesArray?
# 11
> Ok, So I used the tutorial, here is what I have:
>
> ...
When posting code, please use code tags: http://forum.java.sun.com/help.jspa?sec=formatting
> not sure how to load into the namesArray?
Don't know what you mean by that. This is the first time you have mentioned "namesArray". No idea what it is and what you want to do with it.
# 12
Im trying to load the data from file.
I can use the test data to fill my array, but when I try to read from file, im stumped.
I split my code into two classes, ContactSort and Contact.
Contact.java
package mybeans;
import java.util.*;
public class Contact implements Comparable<Contact>{
private final String fname, lname, email, phone, address, city, state, zip;
public Contact(String fname, String lname, String email, String phone, String address, String city, String state, String zip) {
if(fname == null || lname==null)
throw new NullPointerException();
this.fname = fname;
this.lname = lname;
this.email = email;
this.phone = phone;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
}
public String fName() {return fname;}
public String lName() {return lname;}
public String email() {return email;}
public String phone() {return phone;}
public String address() {return address;}
public String city() {return city;}
public String state() {return state;}
public String zip() {return zip;}
public boolean equals(Object o) {
if(!(o instanceof Contact))
return false;
Contact c = (Contact)o;
return c.fname.equals(fname) &&
c.lname.equals(lname) && c.email.equals(email) && c.phone.equals(phone) && c.address.equals(address) && c.city.equals(city) && c.state.equals(state) && c.zip.equals(zip);
}
public int hashCode() {
return 31*fname.hashCode() + lname.hashCode() + email.hashCode() + phone.hashCode() + address.hashCode() + city.hashCode() + state.hashCode() + zip.hashCode();
}
public String toString() {
return fname + "" + lname + email + phone + address + city + state + zip;
}
public int compareTo(Contact c) {
int lastCmp = lname.compareTo(c.lname);
return(lastCmp != 0 ? lastCmp:
fname.compareTo(c.fname));
}
}
ContactSort
package mybeans;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class ContactSort {
private static String fname = "";
private static String lname = "";
private static String fullname = "";
private static String email = "";
private static String phone = "";
private static String streetaddress = "";
private static String city = "";
private static String state = "";
private static String zip = "";
static Contact contactArray [] = {};
public static void main(String[] args) {
/*
this is test code to fill the array.
Contact contactArray [] = {
new Contact("mike", "clayton", "gfgfg", "gfgfg", "sdsd","dsds","sdsd", "11222"),
new Contact("elijah", "smith", "gfgfg", "gfgfg", "sdsd","dsds","sdsd", "11222")
};
*/
List <Contact> contacts = Arrays.asList(contactArray);
Collections.sort(contacts);
System.out.println(contacts);
}
public static void accessFile(){
try{
PrintWriter out = null;
BufferedReader in = new BufferedReader(new FileReader("/Users/custodian/Desktop/list.csv"));
String line;
//Start reading the file while
while ((line = in.readLine()) != null) {
// System.out.println(line);
StringTokenizer st = new StringTokenizer(line, ",");
//This gets us the number of columns:
//Counting tokens while
while (st.hasMoreTokens()){
//System.out.println(st.nextToken());
String fullname = st.nextToken();
StringTokenizer wsp = new StringTokenizer(fullname, " ");
//breaking full name apart while
while(wsp.hasMoreTokens()){
fname = wsp.nextToken();
lname = wsp.nextToken();
}
email = st.nextToken();
phone = st.nextToken();
streetaddress = st.nextToken();
city = st.nextToken();
state = st.nextToken();
zip = st.nextToken();
//This is where I'd like to fill up contactArray.
//not sure what to do.
}
}
in.close();
}catch (FileNotFoundException fnfe)
{System.out.println("File not found");}
catch(IOException ioe){
System.out.println("There was a problem reading the file");
}
}
}
# 13
> Im trying to load the data from file.
> I can use the test data to fill my array, but when I
> try to read from file, im stumped.
>
> ...
I'm sorry, but if you can't be bothered to read what I post, I am not to keen on helping you. Perhaps someone else will.
Good luck though.
# 14
Of course I read what you posted.
So this is where I am now:
I used the example from your link, I have it working. Yes, I am understanding it more.
Thank you for the tuff luv!
I adapted it to my data. It works except> I keep getting the last line of the file. I know when System.out.println for testing.
# 15
So I can read the file. Im having trouble getting all of the lines into my collection.
When I System.out.println the collection I am only getting the last line of the file:
try {
BufferedReader in = new BufferedReader(new FileReader("/Users/custodian/Desktop/list.csv"));
String line;
//Start reading the file while
while ((line = in.readLine()) != null) {
// System.out.println(line);
StringTokenizer st = new StringTokenizer(line, ",");
//Counting tokens while
while (st.hasMoreTokens()){
count++;
//System.out.println(st.nextToken());
fullname = st.nextToken();
StringTokenizer wsp = new StringTokenizer(fullname, " ");
//breaking full name apart while
while(wsp.hasMoreTokens()){
fname = wsp.nextToken();
lname = wsp.nextToken();
}
email = st.nextToken();
phone = st.nextToken();
streetaddress = st.nextToken();
city = st.nextToken();
state = st.nextToken();
zip = st.nextToken();
contactArray = new Contact(fname, lname, email, phone, streetaddress, city, state, zip);
System.out.println(contactArray.toString());
}
}
List <Contact> contacts = Arrays.asList(contactArray);
Collections.sort(contacts);
System.out.println(contacts);
Any ideas?
# 16
Now read what was posted regarding use of the code tags and apply that knowledge. That's what reading things is supposed to do for you. Don't just read it and say "Okay, I read it".