2016-11-18 43 views
0

我有一個要求,我需要有MultiMap,其中不應該有重複的值。 因此,爲此我使用了Guava SetMultimap。 但現在我想保留插入的順序。我如何用SetMultiMap來實現它。 請高度讚賞任何幫助。保留番石榴的插入順序SetMultimap

感謝, 圖莎爾

+4

您是否在尋找'LinkedHashMultimap'? https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/LinkedHashMultimap.html – msandiford

+0

我想要一些可以保留插入順序的東西,並且不包含任何重複值 – Tushar

+0

從上面的鏈接中提供的文檔:「實現Multimap,*不允許重複的鍵值條目*,並且*返回其迭代器遵循將數據添加到multimap中的順序的集合」(重點添加) 。請注意,'LinkedHashMultimap'實現了'SetMultimap'接口(也在文檔鏈接中)。 – msandiford

回答

1

對於那些後來一起走,這裏是一些測試代碼,以顯示LinkedHashMultimap行爲:

private static void assertTrue(boolean x) 
    { 
    if (!x) 
    { 
     throw new AssertionError(); 
    } 
    } 

    public static void main(String[] args) 
    { 
    SetMultimap<String, String> sm = LinkedHashMultimap.create(); 

    List<Map.Entry<String, String>> entries = Arrays.asList(
     new AbstractMap.SimpleEntry<>("z", "z"), 
     new AbstractMap.SimpleEntry<>("a", "a"), 
     new AbstractMap.SimpleEntry<>("x", "x"), 
     new AbstractMap.SimpleEntry<>("z", "x") // Multiple values per key OK 
    ); 

    for (Map.Entry<String, String> entry : entries) 
    { 
     assertTrue(sm.put(entry.getKey(), entry.getValue())); 
    } 

    assertTrue(!sm.put("z", "z")); // Duplicate not added 

    // Check iterator ordering is same as insertion order 
    Iterator<Map.Entry<String, String>> i1 = sm.entries().iterator(); 
    Iterator<Map.Entry<String, String>> i2 = entries.iterator(); 
    while (i1.hasNext() && i2.hasNext()) 
    { 
     assertTrue(i1.next().equals(i2.next())); 
    } 
    // Check same number of elements in both collections 
    assertTrue(!i1.hasNext() && !i2.hasNext()); 
    }