2016-11-18 17 views
0

重複する値がないようにMultiMapを設定する必要があります。 このため私はGuava SetMultimapを使用しました。 しかし、今私は挿入の順序を保持したい。 SetMultiMapでどのように達成できますか? お願いします。よろしくお願いいたします。guava SetMultimapでの挿入順序を維持する

おかげで、一緒に後から来ているものについては Tushar

+4

あなたは 'LinkedHashMultimap'をお探しですか? https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/LinkedHashMultimap.html – msandiford

+0

私は挿入の順序を保持し、重複する値も含まないものを求めています – Tushar

+0

上記のリンクで提供されているドキュメントから: "重複したキー値エントリ*を許さず、イテレータがデータがマルチマップに追加された順序に従うコレクションを返すマルチマップの実装* 。 '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()); 
    } 
関連する問題