guava TreeMultiMap

来源:互联网 发布:如何做页面优化 编辑:程序博客网 时间:2024/05/16 19:45
<pre style="background-color:#ffffff;color:#000000;font-family:'DejaVu Sans Mono';font-size:12.0pt;"><span style="color:#808080;font-style:italic;">/**</span><span style="color:#808080;font-style:italic;"> * Created by jianjun.yu on 15-4-24.</span><span style="color:#808080;font-style:italic;"> */</span>
public class TreeMultimapTest { static class A { private int anInt; private int bnInt; public A(int anInt, int bnInt) { this.anInt = anInt; this.bnInt = bnInt; } @Override public String toString() { return "A{" + "anInt=" + anInt + ", bnInt=" + bnInt + '}'; } } @Test public void test1() { TreeMultimap<Integer, A> treeMultimap = TreeMultimap.create(Ordering.natural(), new Comparator<A>() { @Override public int compare(A o1, A o2) { return Ints.compare(o1.anInt, o2.anInt); } }); Integer key = 1; for (Integer j = 0; j < 10; j++) { treeMultimap.put(key, new A(key, j)); } Assert.assertEquals("A{anInt=1, bnInt=0}", Joiner.on(",").join(treeMultimap.get(key))); } @Test public void test2() { TreeMultimap<Integer, A> treeMultimap = TreeMultimap.create(Ordering.natural(), new Comparator<A>() { @Override public int compare(A o1, A o2) { return Ints.compare(o1.anInt, o2.anInt) != 0 ? Ints.compare(o1.anInt, o2.anInt) : Ints.compare(o1.bnInt, o2.bnInt); } }); Integer key = 1; for (Integer j = 0; j < 10; j++) { treeMultimap.put(key, new A(key, j)); } Assert.assertEquals("A{anInt=1, bnInt=0},A{anInt=1, bnInt=1},A{anInt=1, bnInt=2},A{anInt=1, bnInt=3},A{anInt=1, bnInt=4},A{anInt=1, bnInt=5},A{anInt=1, bnInt=6},A{anInt=1, bnInt=7},A{anInt=1, bnInt=8},A{anInt=1, bnInt=9}", Joiner.on(",").join(treeMultimap.get(key))); } @Test public void testMultimapIterator() { Multimap<Integer, Integer> multimap = MultimapUtils.createSimpleTreeMultimap(); for (Integer i = 0; i < 10; i++) { for (Integer j = 0; j < 10; j++) { multimap.put(i, j); } } for (Integer i = 0; i < 10; i++) { System.out.println(Joiner.on(",").join(multimap.get(i))); } for (Integer i : multimap.keySet()) { Iterator<Integer> iterator = multimap.get(i).iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); if(value % 2 == 0){ iterator.remove(); } } } } @Test public void testMultimapIterator2() { Multimap<Integer, Integer> multimap = MultimapUtils.createSimpleTreeMultimap(); for (Integer i = 0; i < 10; i++) { for (Integer j = 0; j < 10; j++) { multimap.put(i, j); } } try { for (Integer i : multimap.keySet()) { Iterator<Integer> iterator = multimap.get(i).iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); iterator.remove(); } } }catch (ConcurrentModificationException e){ e.printStackTrace(); System.out.println("完全移除value会出现异常"); } }}


0 0