@Test
public void multipleMapExample_with_guava () {
Multimap<String, String> outdoorElements = ArrayListMultimap.create();
outdoorElements.put("fish", "walleye");
outdoorElements.put("fish", "muskellunge");
outdoorElements.put("fish", "bass");
outdoorElements.put("insect", "ants");
outdoorElements.put("insect", "water boatman");
outdoorElements.put("insect", "Lord Howe Island stick insect");
outdoorElements.put("tree", "oak");
outdoorElements.put("tree", "birch");
Collection<String> fishies = outdoorElements.get("fish");
logger.info(fishies);
assertTrue(fishies.size() == 3);
}
输出
[walleye, muskellunge, bass]
@Test
public void multiMap_example_straight_up_java () {
Map<String, List<String>> outdoorElements = new HashMap<String, List<String>>();
putObjects (outdoorElements, "fish", "walleye");
putObjects (outdoorElements, "fish", "muskellunge");
putObjects (outdoorElements, "fish", "bass");
putObjects (outdoorElements, "insect", "ants");
putObjects (outdoorElements, "insect", "water boatman");
putObjects (outdoorElements, "insect", "Lord Howe Island stick insect");
putObjects (outdoorElements, "tree", "oak");
putObjects (outdoorElements, "tree", "birch");
Collection<String> fishies = outdoorElements.get("fish");
logger.info(fishies);
assertTrue(fishies.size() == 3);
}
private void putObjects (Map<String, List<String>> outdoorElements, String key, String value) {
List<String> myClassList = outdoorElements.get(key);
if(myClassList == null) {
myClassList = new ArrayList<String>();
outdoorElements.put(key, myClassList);
}
myClassList.add(value);
}
输出
[walleye, muskellunge, bass]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.leveluplunch.com/java/examples/guava-multimap-example/
内容来源于网络,如有侵权,请联系作者删除!