BiMaps
Well, guess what? This is the sort of situation a BiMap is designed for! And here's how you might use it.
1 2 3 4 5 6 7 8 9 10 11 12 13 | BiMap<String,String> britishToAmerican = HashBiMap.create(); // Initialise and use just like a normal map britishToAmerican.put( "aubergine" , "egglant" ); britishToAmerican.put( "courgette" , "zucchini" ); britishToAmerican.put( "jam" , "jelly" ); System.out.println(britishToAmerican.get( "aubergine" )); // eggplant BiMap<String,String> americanToBritish = britishToAmerican.inverse(); System.out.println(americanToBritish.get( "eggplant" )); // aubergine System.out.println(americanToBritish.get( "zucchini" )); // courgette |
Enforcing uniqueness
Firstly the BiMap enforces uniqueness of it's values, and will give you an illegal argument exception if you try to insert a duplicate value, ie
1 2 | britishToAmerican.put( "pudding" , "dessert" ); britishToAmerican.put( "sweet" , "dessert" ); // IllegalArgumentException. |
forcePut
method that will overwrite the entry with the duplicate value. 1 2 3 4 | britishToAmerican.put( "pudding" , "dessert" ); britishToAmerican.forcePut( "sweet" , "dessert" ); // Overwrites the previous entry System.out.println(britishToAmerican.get( "sweet" )); // dessert System.out.println(britishToAmerican.get( "pudding" )); // null |
Read full article from Tom's Programming Blog: BiMaps
No comments:
Post a Comment