Guide to Google's Guava BiMap - Baeldung

文章推薦指數: 80 %
投票人數:10人

A BiMap (or “bidirectional map”) is a special kind of a map that maintains an inverse view of the map while ensuring that no duplicate ... StartHereCourses ▼▲ RESTwithSpring ThecanonicalreferenceforbuildingaproductiongradeAPIwithSpring LearnSpringSecurity ▼▲ THEuniqueSpringSecurityeducationifyou’reworkingwithJavatoday LearnSpringSecurityCore FocusontheCoreofSpringSecurity5 LearnSpringSecurityOAuth FocusonthenewOAuth2stackinSpringSecurity5 LearnSpring Fromnoexperiencetoactuallybuildingstuff​ LearnSpringDataJPA ThefullguidetopersistencewithSpringDataJPA Guides ▼▲ Persistence ThePersistencewithSpringguides REST TheguidesonbuildingRESTAPIswithSpring Security TheSpringSecurityguides About ▼▲ FullArchive Thehighleveloverviewofallthearticlesonthesite. BaeldungEbooks DiscoverallofoureBooks WriteaboutLinux BecomeawriteronthesiteintheLinuxarea AboutBaeldung AboutBaeldung. GenericTop GetstartedwithSpring5andSpringBoot2,throughtheLearnSpringcourse: >>CHECKOUTTHECOURSE 1.Overview Inthistutorial,we’llshowhowtousetheGoogleGuava'sBiMapinterfaceanditsmultipleimplementations. ABiMap(or“bidirectionalmap”)isaspecialkindofamapthatmaintainsaninverseviewofthemapwhileensuringthatnoduplicatevaluesarepresentandavaluecanalwaysbeusedsafelytogetthekeyback. ThebasicimplementationofBiMapisHashBiMapwhereinternallyitmakesuseoftwoMaps,oneforthekeytovaluemappingandtheotherforthevaluetokeymapping. 2.GoogleGuava'sBiMap Let'shavealookathowtousetheBiMapclass. We'llstartbyaddingtheGoogleGuavalibrarydependencyinthepom.xml: com.google.guava guava 31.0.1-jre Thelatestversionofthedependencycanbecheckedhere. 3.CreatingaBiMap YoucancreateaninstanceofBiMapinmultiplewaysasfollows: IfyouaregoingtodealwithacustomJavaobject,usethecreatemethodfromtheclassHashBiMap: BiMapcapitalCountryBiMap=HashBiMap.create(); Ifwealreadyhaveanexistingmap,youmaycreateaninstanceofaBiMapusinganoverloadedversionofthecreatemethodfromaclassHashBiMap: MapcapitalCountryBiMap=newHashMap<>(); //... HashBiMap.create(capitalCountryBiMap); IfyouaregoingtodealwithakeyoftypeEnum,usethecreatemethodfromtheclassEnumHashBiMap: BiMapoperationStringBiMap=EnumHashBiMap.create(MyEnum.class); Ifyouintendtocreateanimmutablemap,usetheImmutableBiMapclass(whichfollowsabuilderpattern): BiMapcapitalCountryBiMap =newImmutableBiMap.Builder<>() .put("NewDelhi","India") .build(); 4.UsingtheBiMap Let’sstartwithasimpleexampleshowingtheusageofBiMap,wherewecangetakeybasedonavalueandavaluebasedonakey: @Test publicvoidgivenBiMap_whenQueryByValue_shouldReturnKey(){ BiMapcapitalCountryBiMap=HashBiMap.create(); capitalCountryBiMap.put("NewDelhi","India"); capitalCountryBiMap.put("Washington,D.C.","USA"); capitalCountryBiMap.put("Moscow","Russia"); StringkeyFromBiMap=capitalCountryBiMap.inverse().get("Russia"); StringvalueFromBiMap=capitalCountryBiMap.get("Washington,D.C."); assertEquals("Moscow",keyFromBiMap); assertEquals("USA",valueFromBiMap); } Note:theinversemethodabovereturnstheinverseviewoftheBiMap,whichmapseachoftheBiMap'svaluestoitsassociatedkeys. BiMapthrowsanIllegalArgumentExceptionwhenwetrytostoreaduplicatevaluetwice. Let'sseeanexampleofthesame: @Test(expected=IllegalArgumentException.class) publicvoidgivenBiMap_whenSameValueIsPresent_shouldThrowException(){ BiMapcapitalCountryBiMap=HashBiMap.create(); capitalCountryBiMap.put("Mumbai","India"); capitalCountryBiMap.put("Washington,D.C.","USA"); capitalCountryBiMap.put("Moscow","Russia"); capitalCountryBiMap.put("NewDelhi","India"); } IfwewishtooverridethevaluealreadypresentinBiMap,wecanmakeuseoftheforcePutmethod: @Test publicvoidgivenSameValueIsPresent_whenForcePut_completesSuccessfully(){ BiMapcapitalCountryBiMap=HashBiMap.create(); capitalCountryBiMap.put("Mumbai","India"); capitalCountryBiMap.put("Washington,D.C.","USA"); capitalCountryBiMap.put("Moscow","Russia"); capitalCountryBiMap.forcePut("NewDelhi","India"); assertEquals("USA",capitalCountryBiMap.get("Washington,D.C.")); assertEquals("Washington,D.C.",capitalCountryBiMap.inverse().get("USA")); } 5.Conclusion Inthisconcisetutorial,weillustratedexamplesofusingtheBiMapintheGuavalibrary.Itispredominantlyusedtogetakeybasedonthevaluefromthemap. TheimplementationoftheseexamplescanbefoundintheGitHubproject–thisisaMaven-basedproject,soitshouldbeeasytoimportandrunas-is. Genericbottom GetstartedwithSpring5andSpringBoot2,throughtheLearnSpringcourse: >>CHECKOUTTHECOURSE Genericfooterbanner LearningtobuildyourAPIwithSpring? DownloadtheE-book Commentsareclosedonthisarticle! Genericsidebarbanner BuildingaRESTAPIwithSpring5? DownloadtheE-book



請為這篇文章評分?