/* * [TestHashMapInit.java] * * Summary: example initialising java.util.HashMap from a CSV file. * * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2011-10-15 initial version */ 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"; // sample test file private static final Map ABBR_TO_STATE; /** * lookup 2-char abbr to get state name */ private static final Map abbrToState = new HashMap<>( 149 /* capacity */, 0.75f /* loadfactor */ ); static { // initialise the HashMap from a CSV file at class load time. 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" ); // This gives you a Map of Entry items. This is not suitable for sorting. for ( Entry entry : ABBR_TO_STATE.entrySet() ) { // prints lines of the form NY=New York // in effectively random order, but will be in the same order as keySet() and values(). out.println( entry ); } } }