private void assertOrderingReadOnly(Multimap<String, Integer> multimap) { assertThat(multimap.get("foo")).containsExactly(5, 3).inOrder(); assertThat(multimap.get("bar")).containsExactly(4, 1).inOrder(); assertThat(multimap.get("cow")).contains(2); assertThat(multimap.keySet()).containsExactly("foo", "bar", "cow").inOrder(); assertThat(multimap.values()).containsExactly(5, 4, 3, 2, 1).inOrder(); Iterator<Map.Entry<String, Integer>> entryIterator = multimap.entries().iterator(); assertEquals(Maps.immutableEntry("foo", 5), entryIterator.next()); assertEquals(Maps.immutableEntry("bar", 4), entryIterator.next()); assertEquals(Maps.immutableEntry("foo", 3), entryIterator.next()); assertEquals(Maps.immutableEntry("cow", 2), entryIterator.next()); assertEquals(Maps.immutableEntry("bar", 1), entryIterator.next()); Iterator<Map.Entry<String, Collection<Integer>>> collectionIterator = multimap.asMap().entrySet().iterator(); Map.Entry<String, Collection<Integer>> entry = collectionIterator.next(); assertEquals("foo", entry.getKey()); assertThat(entry.getValue()).containsExactly(5, 3).inOrder(); entry = collectionIterator.next(); assertEquals("bar", entry.getKey()); assertThat(entry.getValue()).containsExactly(4, 1).inOrder(); entry = collectionIterator.next(); assertEquals("cow", entry.getKey()); assertThat(entry.getValue()).contains(2); }
public void testConstrainedMapLegal() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); map.put(TEST_KEY, TEST_VALUE); constrained.put("foo", 1); map.putAll(ImmutableMap.of("bar", 2)); constrained.putAll(ImmutableMap.of("baz", 3)); assertTrue(map.equals(constrained)); assertTrue(constrained.equals(map)); assertEquals(map.entrySet(), constrained.entrySet()); assertEquals(map.keySet(), constrained.keySet()); assertEquals(HashMultiset.create(map.values()), HashMultiset.create(constrained.values())); assertFalse(map.values() instanceof Serializable); assertEquals(map.toString(), constrained.toString()); assertEquals(map.hashCode(), constrained.hashCode()); ASSERT .that(map.entrySet()) .has() .allOf( Maps.immutableEntry(TEST_KEY, TEST_VALUE), Maps.immutableEntry("foo", 1), Maps.immutableEntry("bar", 2), Maps.immutableEntry("baz", 3)) .inOrder(); }
@GwtIncompatible // unreasonably slow public void testEntriesIteration() { @SuppressWarnings("unchecked") Set<Entry<String, Integer>> set = Sets.newLinkedHashSet( asList( Maps.immutableEntry("foo", 2), Maps.immutableEntry("foo", 3), Maps.immutableEntry("bar", 4), Maps.immutableEntry("bar", 5), Maps.immutableEntry("foo", 6))); new IteratorTester<Entry<String, Integer>>( 6, MODIFIABLE, set, IteratorTester.KnownOrder.KNOWN_ORDER) { private Multimap<String, Integer> multimap; @Override protected Iterator<Entry<String, Integer>> newTargetIterator() { multimap = LinkedHashMultimap.create(); multimap.putAll("foo", asList(2, 3)); multimap.putAll("bar", asList(4, 5)); multimap.putAll("foo", asList(6)); return multimap.entries().iterator(); } @Override protected void verify(List<Entry<String, Integer>> elements) { assertEquals(newHashSet(elements), multimap.entries()); } }.test(); }
@GwtIncompatible // unreasonably slow public void testAsSetIteration() { @SuppressWarnings("unchecked") Set<Entry<String, Collection<Integer>>> set = newLinkedHashSet( asList( Maps.immutableEntry("foo", (Collection<Integer>) Sets.newHashSet(2, 3, 6)), Maps.immutableEntry("bar", (Collection<Integer>) Sets.newHashSet(4, 5, 10, 11)), Maps.immutableEntry("baz", (Collection<Integer>) Sets.newHashSet(7, 8)), Maps.immutableEntry("dog", (Collection<Integer>) Sets.newHashSet(9)), Maps.immutableEntry("cat", (Collection<Integer>) Sets.newHashSet(12, 13, 14)))); new IteratorTester<Entry<String, Collection<Integer>>>( 6, MODIFIABLE, set, IteratorTester.KnownOrder.KNOWN_ORDER) { private Multimap<String, Integer> multimap; @Override protected Iterator<Entry<String, Collection<Integer>>> newTargetIterator() { multimap = LinkedHashMultimap.create(); multimap.putAll("foo", asList(2, 3)); multimap.putAll("bar", asList(4, 5)); multimap.putAll("foo", asList(6)); multimap.putAll("baz", asList(7, 8)); multimap.putAll("dog", asList(9)); multimap.putAll("bar", asList(10, 11)); multimap.putAll("cat", asList(12, 13, 14)); return multimap.asMap().entrySet().iterator(); } @Override protected void verify(List<Entry<String, Collection<Integer>>> elements) { assertEquals(newHashSet(elements), multimap.asMap().entrySet()); } }.test(); }
@Override public boolean remove(@Nullable Object o) { if (o instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) o; Map<C, V> row = Maps.safeGet(rowMap(), cell.getRowKey()); return row != null && Collections2.safeRemove( row.entrySet(), Maps.immutableEntry(cell.getColumnKey(), cell.getValue())); } return false; }
public void testBuilder_withImmutableEntryAndNullContents() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry("one", (Integer) null)); fail(); } catch (NullPointerException expected) { } try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } }
private String getPrimaryNetworkServiceName() { // TODO This would be faster (but harder to test?) if we just launched scutil once // and communicated with it line-by-line using stdin/stdout String output = runScutil("show State:/Network/Global/IPv4"); log.trace(output); Map<String, String> dictionary = Maps.parseDictionary(output.toString(), SCUTIL_LINE, false); String primaryInterface = verifyKey("PrimaryInterface", dictionary, "scutil", output); output = runNetworkSetup("-listnetworkserviceorder"); log.trace(output); dictionary = Maps.parseDictionary(output.toString(), NETWORKSETUP_LISTORDER_LINE, true); String userDefinedName = verifyKey(primaryInterface, dictionary, "networksetup -listnetworksetuporder", output); networkService = userDefinedName; return userDefinedName; }
public void testNefariousMapPutAll() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); Map<String, Integer> onceIterable = onceIterableMap("foo", 1); constrained.putAll(onceIterable); assertEquals((Integer) 1, constrained.get("foo")); }
public void testConstrainedMapIllegal() { Map<String, Integer> map = Maps.newLinkedHashMap(); Map<String, Integer> constrained = MapConstraints.constrainedMap(map, TEST_CONSTRAINT); try { constrained.put(TEST_KEY, TEST_VALUE); fail("TestKeyException expected"); } catch (TestKeyException expected) { } try { constrained.put("baz", TEST_VALUE); fail("TestValueException expected"); } catch (TestValueException expected) { } try { constrained.put(TEST_KEY, 3); fail("TestKeyException expected"); } catch (TestKeyException expected) { } try { constrained.putAll(ImmutableMap.of("baz", 3, TEST_KEY, 4)); fail("TestKeyException expected"); } catch (TestKeyException expected) { } assertEquals(Collections.emptySet(), map.entrySet()); assertEquals(Collections.emptySet(), constrained.entrySet()); }
@Override protected Map<String, Integer> makePopulatedMap() { BiMap<String, Integer> bimap = HashBiMap.create(); bimap.put("foo", 1); bimap.put("bar", 2); return Maps.unmodifiableBiMap(bimap); }
@Test public void testCollectionInstance() { Maps.newLinkedHashMap(); Lists.newArrayList(); Sets.newHashSet(); ObjectArrays.newArray(Integer.class, 10); }
@NonNull public IAndroidTarget[] getMissingTargets() { synchronized (mLocalPackages) { if (mCachedMissingTargets == null) { Map<MissingTarget, MissingTarget> result = Maps.newHashMap(); Set<ISystemImage> seen = Sets.newHashSet(); for (IAndroidTarget target : getTargets()) { Collections.addAll(seen, target.getSystemImages()); } for (LocalPkgInfo local : getPkgsInfos(PkgType.PKG_ADDON_SYS_IMAGE)) { LocalAddonSysImgPkgInfo info = (LocalAddonSysImgPkgInfo) local; ISystemImage image = info.getSystemImage(); if (!seen.contains(image)) { addOrphanedSystemImage(image, info.getDesc(), result); } } for (LocalPkgInfo local : getPkgsInfos(PkgType.PKG_SYS_IMAGE)) { LocalSysImgPkgInfo info = (LocalSysImgPkgInfo) local; ISystemImage image = info.getSystemImage(); if (!seen.contains(image)) { addOrphanedSystemImage(image, info.getDesc(), result); } } mCachedMissingTargets = result.keySet(); } return mCachedMissingTargets.toArray(new IAndroidTarget[mCachedMissingTargets.size()]); } }
/** * 初始化起始点 <br> * 初始时,S只包含起点s;U包含除s外的其他顶点,且U中顶点的距离为"起点s到该顶点的距离" [例如,U中顶点v的距离为(s,v)的长度,然后s和v不相邻,则v的距离为∞]。 * * @param source 起始节点的Id * @param map 全局地图 * @param closeSet 已经关闭的节点列表 * @return */ @SuppressWarnings("unchecked") public Maps.Node<T> init(T source, Maps<T> map, Set<T> closeSet) { Map<T, Maps.Node<T>> nodeMap = map.getNodes(); Maps.Node<T> startNode = nodeMap.get(source); // 将初始节点放到close close.add(startNode); // 将其他节点放到open for (Maps.Node<T> node : nodeMap.values()) { if (!closeSet.contains(node.getId()) && !node.getId().equals(source)) { this.open.add(node); } } // 初始路径 T startNodeId = startNode.getId(); for (Entry<Maps.Node<T>, Integer> entry : startNode.getChilds().entrySet()) { Maps.Node<T> node = entry.getKey(); if (open.contains(node)) { T nodeId = node.getId(); path.put(node, entry.getValue()); pathInfo.put(nodeId, new ArrayList<T>(Arrays.asList(startNodeId, nodeId))); } } for (Maps.Node<T> node : nodeMap.values()) { if (open.contains(node) && !path.containsKey(node)) { path.put(node, Integer.MAX_VALUE); pathInfo.put(node.getId(), new ArrayList<T>(Arrays.asList(startNodeId))); } } this.startNode = startNode; this.map = map; return startNode; }
Iterable<WhenHttpRequest> findWhensMatchingRequest( ImmutableMap<String, RestxSpec> allSpecs, RestxRequest restxRequest) { Collection<WhenHttpRequest> matchingRequestsSpecs = Lists.newArrayList(); for (Map.Entry<String, RestxSpec> spec : allSpecs.entrySet()) { for (When when : spec.getValue().getWhens()) { if (when instanceof WhenHttpRequest) { WhenHttpRequest request = (WhenHttpRequest) when; String requestPath = request.getPath(); if (!requestPath.startsWith("/")) { requestPath = "/" + requestPath; } StdRequest stdRequest = StdRequest.builder() .setBaseUri("http://restx.io") // baseUri is required but we won't use it .setHttpMethod(request.getMethod()) .setFullPath(requestPath) .build(); if (restxRequest.getHttpMethod().equals(stdRequest.getHttpMethod()) && restxRequest.getRestxPath().equals(stdRequest.getRestxPath())) { MapDifference<String, ImmutableList<String>> difference = Maps.difference(restxRequest.getQueryParams(), stdRequest.getQueryParams()); if (difference.entriesOnlyOnRight().isEmpty() && difference.entriesDiffering().isEmpty()) { matchingRequestsSpecs.add(request); break; } } } } } return matchingRequestsSpecs; }
/** * Returns a newly-created immutable bimap. * * @throws IllegalArgumentException if duplicate keys or values were added */ @Override public ImmutableBiMap<K, V> build() { switch (size) { case 0: return of(); case 1: return of(entries[0].getKey(), entries[0].getValue()); default: /* * If entries is full, then this implementation may end up using the entries array * directly and writing over the entry objects with non-terminal entries, but this is * safe; if this Builder is used further, it will grow the entries array (so it can't * affect the original array), and future build() calls will always copy any entry * objects that cannot be safely reused. */ if (valueComparator != null) { if (entriesUsed) { entries = Arrays.copyOf(entries, size); } Arrays.sort( entries, 0, size, Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction())); } entriesUsed = size == entries.length; return RegularImmutableBiMap.fromEntryArray(size, entries); } }
@GwtIncompatible // java.io.ObjectInputStream private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); int distinctElements = Serialization.readCount(stream); setBackingMap(Maps.<E, Count>newHashMap()); Serialization.populateMultiset(this, stream, distinctElements); }
@Test public void should_format_Map() { Map<String, Class<?>> map = new LinkedHashMap<String, Class<?>>(); map.put("One", String.class); map.put("Two", File.class); assertEquals("{'One'=java.lang.String, 'Two'=java.io.File}", Maps.format(map)); }
public NBTStorage(final File file, final String name) { this.root = (Map<String, Tag>) Maps.newHashMap(); this.file = file; if (!this.file.exists()) { this.create(); } this.name = name; }
@GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); expectedValuesPerKey = stream.readInt(); int distinctKeys = Serialization.readCount(stream); setMap(new LinkedHashMap<K, Collection<V>>(Maps.capacity(distinctKeys))); linkedEntries = new LinkedHashSet<Map.Entry<K, V>>(distinctKeys * expectedValuesPerKey); Serialization.populateMultimap(this, stream, distinctKeys); linkedEntries.clear(); // will clear and repopulate entries for (int i = 0; i < size(); i++) { @SuppressWarnings("unchecked") // reading data stored by writeObject K key = (K) stream.readObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject V value = (V) stream.readObject(); linkedEntries.add(Maps.immutableEntry(key, value)); } }
private int repeatInternal( @NotNull PseudocodeImpl originalPseudocode, @Nullable Label startLabel, @Nullable Label finishLabel, int labelCount) { Integer startIndex = startLabel != null ? ((PseudocodeLabel) startLabel).getTargetInstructionIndex() : Integer.valueOf(0); assert startIndex != null; Integer finishIndex = finishLabel != null ? ((PseudocodeLabel) finishLabel).getTargetInstructionIndex() : Integer.valueOf(originalPseudocode.mutableInstructionList.size()); assert finishIndex != null; Map<Label, Label> originalToCopy = Maps.newLinkedHashMap(); Multimap<Instruction, Label> originalLabelsForInstruction = HashMultimap.create(); for (PseudocodeLabel label : originalPseudocode.labels) { Integer index = label.getTargetInstructionIndex(); if (index == null) continue; // label is not bounded yet if (label == startLabel || label == finishLabel) continue; if (startIndex <= index && index <= finishIndex) { originalToCopy.put(label, label.copy(labelCount++)); originalLabelsForInstruction.put(getJumpTarget(label), label); } } for (Label label : originalToCopy.values()) { labels.add((PseudocodeLabel) label); } for (int index = startIndex; index < finishIndex; index++) { Instruction originalInstruction = originalPseudocode.mutableInstructionList.get(index); repeatLabelsBindingForInstruction( originalInstruction, originalToCopy, originalLabelsForInstruction); Instruction copy = copyInstruction(originalInstruction, originalToCopy); addInstruction(copy); if (originalInstruction == originalPseudocode.errorInstruction && copy instanceof SubroutineExitInstruction) { errorInstruction = (SubroutineExitInstruction) copy; } if (originalInstruction == originalPseudocode.exitInstruction && copy instanceof SubroutineExitInstruction) { exitInstruction = (SubroutineExitInstruction) copy; } if (originalInstruction == originalPseudocode.sinkInstruction && copy instanceof SubroutineSinkInstruction) { sinkInstruction = (SubroutineSinkInstruction) copy; } } if (finishIndex < mutableInstructionList.size()) { repeatLabelsBindingForInstruction( originalPseudocode.mutableInstructionList.get(finishIndex), originalToCopy, originalLabelsForInstruction); } return labelCount; }
private void writeDelegateMethods( final ClassVisitor visitor, final Type generatedType, StructSchema<?> delegateSchema, Set<Class<?>> typesToDelegate) { Class<?> delegateClass = delegateSchema.getType().getConcreteClass(); Type delegateType = Type.getType(delegateClass); Map<Equivalence.Wrapper<Method>, Map<Class<?>, Method>> methodsToDelegate = Maps.newHashMap(); for (Class<?> typeToDelegate : typesToDelegate) { for (Method methodToDelegate : typeToDelegate.getMethods()) { if (ModelSchemaUtils.isIgnoredMethod(methodToDelegate)) { continue; } Equivalence.Wrapper<Method> methodKey = METHOD_EQUIVALENCE.wrap(methodToDelegate); Map<Class<?>, Method> methodsByReturnType = methodsToDelegate.get(methodKey); if (methodsByReturnType == null) { methodsByReturnType = Maps.newHashMap(); methodsToDelegate.put(methodKey, methodsByReturnType); } methodsByReturnType.put(methodToDelegate.getReturnType(), methodToDelegate); } } Set<Equivalence.Wrapper<Method>> delegateMethodKeys = ImmutableSet.copyOf( Iterables.transform( Arrays.asList(delegateClass.getMethods()), new Function<Method, Equivalence.Wrapper<Method>>() { @Override public Equivalence.Wrapper<Method> apply(Method method) { return METHOD_EQUIVALENCE.wrap(method); } })); for (Map.Entry<Equivalence.Wrapper<Method>, Map<Class<?>, Method>> entry : methodsToDelegate.entrySet()) { Equivalence.Wrapper<Method> methodKey = entry.getKey(); if (!delegateMethodKeys.contains(methodKey)) { continue; } Map<Class<?>, Method> methodsByReturnType = entry.getValue(); for (Method methodToDelegate : methodsByReturnType.values()) { writeDelegatedMethod(visitor, generatedType, delegateType, methodToDelegate); } } }
@Override public void testRow() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<Integer, Character> expected = Maps.newHashMap(); expected.put(1, 'a'); expected.put(3, 'c'); expected.put(2, null); assertEquals(expected, table.row("foo")); }
@Override public void testColumn() { table = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c'); Map<String, Character> expected = Maps.newHashMap(); expected.put("foo", 'a'); expected.put("bar", 'b'); expected.put("cat", null); assertEquals(expected, table.column(1)); }
@GwtIncompatible("java.io.ObjectOutputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; int distinctKeys = Serialization.readCount(stream); Map<K, Collection<V>> map = Maps.newHashMap(); setMap(map); Serialization.populateMultimap(this, stream, distinctKeys); }
public void testFromHashMap() { Map<String, Integer> hashMap = Maps.newLinkedHashMap(); hashMap.put("one", 1); hashMap.put("two", 2); ImmutableBiMap<String, Integer> bimap = ImmutableBiMap.copyOf(ImmutableMap.of("one", 1, "two", 2)); assertMapEquals(bimap, "one", 1, "two", 2); assertMapEquals(bimap.inverse(), 1, "one", 2, "two"); }
private static Map<ClassDescriptor, JetType> getSuperclassToSupertypeMap( ClassDescriptor containingClass) { Map<ClassDescriptor, JetType> superclassToSupertype = Maps.newHashMap(); for (JetType supertype : TypeUtils.getAllSupertypes(containingClass.getDefaultType())) { ClassifierDescriptor superclass = supertype.getConstructor().getDeclarationDescriptor(); assert superclass instanceof ClassDescriptor; superclassToSupertype.put((ClassDescriptor) superclass, supertype); } return superclassToSupertype; }
/** Returns document counts for each partition. */ Map<Object, Integer> getDocumentCountByPartition(List<Document> documents) { return ImmutableMap.copyOf( Maps.transformValues( getDocumentsByPartition(documents).asMap(), new Function<Collection<Document>, Integer>() { public Integer apply(Collection<Document> documents) { return documents.size(); } })); }
public void testMutableValues() { IntHolder holderA = new IntHolder(1); IntHolder holderB = new IntHolder(2); Map<String, IntHolder> map = ImmutableMap.of("a", holderA, "b", holderB); holderA.value = 3; assertTrue(map.entrySet().contains(Maps.immutableEntry("a", new IntHolder(3)))); Map<String, Integer> intMap = ImmutableMap.of("a", 3, "b", 2); assertEquals(intMap.hashCode(), map.entrySet().hashCode()); assertEquals(intMap.hashCode(), map.hashCode()); }
public void testBuilderPutImmutableEntryWithNullKeyFailsAtomically() { Builder<String, Integer> builder = new Builder<String, Integer>(); try { builder.put(Maps.immutableEntry((String) null, 1)); fail(); } catch (NullPointerException expected) { } builder.put("foo", 2); assertMapEquals(builder.build(), "foo", 2); }
private void testRangesByLowerBounds( TreeRangeSet<Integer> rangeSet, Iterable<Range<Integer>> expectedRanges) { NavigableMap<Cut<Integer>, Range<Integer>> expectedRangesByLowerBound = Maps.newTreeMap(); for (Range<Integer> range : expectedRanges) { expectedRangesByLowerBound.put(range.lowerBound, range); } NavigableMap<Cut<Integer>, Range<Integer>> rangesByLowerBound = rangeSet.rangesByLowerBound; testNavigationAgainstExpected(expectedRangesByLowerBound, rangesByLowerBound, CUTS_TO_TEST); }