package com.mindprod.example;
import com.mindprod.csv.CSVReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static java.lang.System.*;
/**
* example initialising java.util.HashMap from a CSV file.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2011-10-15 initial version
* @since 2011-10-15
*/
@SuppressWarnings( { "UnusedAssignment" } )
public final class TestHashMapInit
{
/**
* where to get the pairs to initialise the HashMap
*/
private static final String STATES_FILE = "E:/com/mindprod/example/states.csv";
private static final Map<String, String> ABBR_TO_STATE;
/**
* lookup 2-char abbr to get state name
*/
private static final Map<String, String> abbrToState = new HashMap<>( 149
,
0.75f
);
static
{
try
{
final CSVReader r = new CSVReader( new FileReader( new File( STATES_FILE ) ) );
try
{
while ( true )
{
final String abbr = r.get();
final String state = r.get();
r.skipToNextLine();
abbrToState.put( abbr, state );
}
}
catch ( EOFException e )
{
r.close();
}
}
catch ( Exception e )
{
err.println();
e.printStackTrace( System.err );
err.println( "Fatal error: Problem initialising state abbr to state HashMap" );
System.exit( 2 );
}
ABBR_TO_STATE = Collections.unmodifiableMap( abbrToState );
out.println( ABBR_TO_STATE.size() + " abbreviations loaded from " + STATES_FILE );
}
/**
* Sample code to TEST HashMap initialisation. requires JDK 1.5+
*
* @param args not used
*/
@SuppressWarnings( "unchecked" )
public static void main( String[] args )
{
out.println( "enumerate all the key/value Entries in the HashMap" );
for ( Entry<String, String> entry : ABBR_TO_STATE.entrySet() )
{
out.println( entry );
}
}
}