Google Guava API学习笔记(2):集合
不可变集合 Immutable Collections
例子
public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of( "red", "orange", "yellow", "green", "blue", "purple");class Foo { Set<Bar> bars; Foo(Set<Bar> bars) { this.bars = ImmutableSet.copyOf(bars); // defensive copy! }}
public static final ImmutableSet<Color> GOOGLE_COLORS = ImmutableSet.<Color>builder() .addAll(WEBSAFE_COLORS) .add(new Color(0, 191, 255)) .build();
ImmutableSet<String> foobar = ImmutableSet.of("foo", "bar", "baz");thingamajig(foobar);void thingamajig(Collection<String> collection) { ImmutableList<String> defensiveCopy = ImmutableList.copyOf(collection); ...}
Multiset<String> wordsMultiset = HashMultiset.create();wordsMultiset.addAll(words);
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();weightedGraph.put(v1, v2, 4);weightedGraph.put(v1, v3, 20);weightedGraph.put(v2, v3, 5);weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5
List<TypeThatsTooLongForItsOwnGood> list = Lists.newArrayList();Map<KeyType, LongishValueType> map = Maps.newLinkedHashMap();
List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<>();
Set<Type> copySet = Sets.newHashSet(elements);List<String> theseElements = Lists.newArrayList("alpha", "beta", "gamma");
List<Type> exactly100 = Lists.newArrayListWithCapacity(100);List<Type> approx100 = Lists.newArrayListWithExpectedSize(100);Set<Type> approx100Set = Sets.newHashSetWithExpectedSize(100);
Multiset<String> multiset = HashMultiset.create();
List<Integer> countUp = Ints.asList(1, 2, 3, 4, 5);List<Integer> countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1}List<List<Integer>> parts = Lists.partition(countUp, 2); // {{1, 2}, {3, 4}, {5}}
Set<String> wordsWithPrimeLength = ImmutableSet.of("one", "two", "three", "six", "seven", "eight");Set<String> primes = ImmutableSet.of("two", "three", "five", "seven");SetView<String> intersection = Sets.intersection(primes, wordsWithPrimeLength); // contains "two", "three", "seven"// I can use intersection as a Set directly, but copying it can be more efficient if I use it a lot.return intersection.immutableCopy();