Google Guava Multimap代码示例

x33g5p2x  于2022-09-16 转载在 Java  
字(1.9k)|赞(0)|评价(0)|浏览(337)

Multimap

@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]

Without guava

@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]

相关文章

最新文章

更多