package com.mindprod.example;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static java.lang.System.*;
/**
* example use of java.util.HashMap autoboxing. Sample code to TEST HashMap with automatic boxing.
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2009-01-01 initial version
* @since 2009-01-01
*/
@SuppressWarnings( { "UnusedAssignment" } )
public final class TestHashMapAutoBoxing
{
/**
* Sample code to TEST HashMap with automatic boxing. requires JDK 1.5+
*
* @param args not used
*/
@SuppressWarnings( "unchecked" )
public static void main( String[] args )
{
final Map<String, Integer> h = new HashMap<>( 149 , 0.75f );
{
h.put( "inch", 1 );
h.put( "foot", 12 );
h.put( "yard", 36 );
h.put( "mile", 3760 * 36 );
}
int inches = h.get( "foot" );
out.println( inches );
out.println( "enumerate all the keys in the HashMap" );
out.println( h.keySet().getClass() );
for ( String key : h.keySet() )
{
int value = h.get( key );
out.println( key + " " + value );
}
out.println( "enumerate all the values in the HashMap" );
out.println( h.values().getClass() );
for ( int value : h.values() )
{
out.println( value );
}
out.println( "enumerate all the key/value Entries in the HashMap" );
for ( Map.Entry<String, Integer> entry : h.entrySet() )
{
out.println( "as Entry: " + entry );
String key = entry.getKey();
int value = entry.getValue();
out.println( "separately: " + key + " " + value );
}
Set<String> justKeys = h.keySet();
String[] keys = justKeys.toArray( new String[ justKeys.size() ] );
Collection<Integer> justValues = h.values();
Integer[] values = justValues.toArray( new Integer[ justValues.size() ] );
Set<Map.Entry<String, Integer>> justEntries = h.entrySet();
Map.Entry<String, Integer>[] keyValuePairs = justEntries.toArray( new Map.Entry[ justEntries.size() ] );
out.println( "enumerate all the key/value Entries in the HashMap using Java 1.8 lambda dual foreach" );
h.forEach( ( unit, measure ) ->
{
out.println( unit + " -> " + measure );
} );
}
}