/* * [TestHashMapRemove.java] * * Summary: example use of java.util.HashMap. How to iterate through a HashMap removing some of the elements. * * 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 2008-06-19 */ package com.mindprod.example; import java.util.HashMap; import java.util.Iterator; import static java.lang.System.*; /** * example use of java.util.HashMap. How to iterate through a HashMap removing some of the elements. *

* Requires JDK 1.5+. * * @author Roedy Green, Canadian Mind Products * @version 1.0 2008-06-19 * @since 2008-06-19 */ @SuppressWarnings( { "UnusedAssignment" } ) public final class TestHashMapRemove { /** * How to iterate through a HashMap removing some of the elements. * * @param args not used */ @SuppressWarnings( "unchecked" ) public static void main( String[] args ) { // create a new HashMap HashMap h = new HashMap<>( 149 /* capacity */, 0.75f /* loadfactor */ ); // add some key/value pairs to the HashMap h.put( "WA", "Washington" ); h.put( "NY", "New York" ); h.put( "RI", "Rhode Island" ); h.put( "CA", "California" ); h.put( "BC", "British Columbia" ); h.put( "OR", "Oregon" ); // To just remove an individual element, you don't need iter.remove. h.remove( "CA" ); for ( Iterator iter = h.values().iterator(); iter.hasNext(); ) { String item = iter.next(); if ( item.indexOf( ' ' ) > 0 ) { // remove from any state with a space in its long name. iter.remove();// avoids ConcurrentModificationException } } // see what's left for ( String stateAbbr : h.keySet() ) { out.println( stateAbbr ); } // prints OR WA (no special order with keySet) } // end main }