Java Code Examples for com.google.common.collect.ImmutableMultimap

The following are top voted examples for showing how to use com.google.common.collect.ImmutableMultimap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: ExtraCollection.java   Source Code and License 6 votes vote down vote up
default void use() {
  ImmutableExtraCollection.of(
      ImmutableList.<String>of(),
      ImmutableMultimap.<Integer, String>of(),
      ImmutableMultimap.<Integer, String>of(),
      ImmutableMultimap.<Integer, String>of(),
      ImmutableBiMap.<Integer, String>of());
  ImmutableExtraCollection.of();
  ImmutableExtraCollection collection = ImmutableExtraCollection.builder()
      .addBag("2", "2")
      .putIndex(1, "2", "3", "4")
      .putAllIndex(1, Arrays.asList("2", "3", "4"))
      .putIndex(2, "5")
      .putIndexList(1, "")
      .putIndexSet(2, "2")
      .putAllIndexSet(2, Arrays.asList("3", "4"))
      .putBiMap(1, "a")
      .putBiMap(2, "b")
      .putAllBiMap(Collections.singletonMap(3, "c"))
      .build();

  collection.bag().count("2");
  collection.index().get(1);
  collection.indexList().get(1);
  collection.indexSet().get(2);
}
 
Example 2
Project: de.flapdoodle.solid   File: Multimaps.java   Source Code and License 6 votes vote down vote up
public static <K,V> ImmutableList<ImmutableMap<K, V>> flatten(ImmutableMultimap<K, V> src) {
	ImmutableList.Builder<ImmutableMap<K, V>> listBuilder=ImmutableList.builder();
	
	if (!src.isEmpty()) {
		ImmutableMap<K, Collection<V>> map = src.asMap();
		int entries=map.values().stream().reduce(1, (s,l) -> s*l.size(), (a,b) -> a*b);
		
		ImmutableList<Line<K,V>> lines = map.entrySet().stream()
				.map(e -> new Line<>(e.getKey(), e.getValue()))
				.collect(ImmutableList.toImmutableList());
		
		for (int i=0;i<entries;i++) {
			ImmutableMap.Builder<K, V> mapBuilder = ImmutableMap.builder();
			
			int fact=1;
			for (Line<K,V> line: lines) {
				mapBuilder.put(line.key, line.get((i/fact) % line.values.length));
				fact=fact*line.values.length;
			}
			
			listBuilder.add(mapBuilder.build());
		}
	}
	return listBuilder.build();
}
 
Example 3
Project: GitHub   File: Gsons.java   Source Code and License 6 votes vote down vote up
@Override
public Multimap<Character, Map.Entry<String, ValueAttribute>> apply(Iterable<ValueAttribute> attributes) {
  ImmutableMultimap.Builder<Character, Map.Entry<String, ValueAttribute>> builder = ImmutableMultimap.builder();

  for (ValueAttribute attribute : attributes) {
    String serializedName = attribute.getMarshaledName();
    builder.put(serializedName.charAt(0), Maps.immutableEntry(serializedName, attribute));

    for (String alternateName : attribute.getAlternateSerializedNames()) {
      if (!alternateName.isEmpty()) {
        builder.put(alternateName.charAt(0), Maps.immutableEntry(alternateName, attribute));
      }
    }
  }

  return builder.build();
}
 
Example 4
Project: mug   File: BiStreamTest.java   Source Code and License 6 votes vote down vote up
@Test public void testOf() {
  assertKeyValues(BiStream.of("one", 1))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1, "two", 2))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2, "three", 3))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1, "two", 2, "three", 3))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2, "three", 3, "four", 4))
      .containsExactlyEntriesIn(ImmutableMultimap.of(
          "one", 1, "two", 2, "three", 3, "four", 4))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5))
      .containsExactlyEntriesIn(ImmutableMultimap.of(
          "one", 1, "two", 2, "three", 3, "four", 4, "five", 5))
      .inOrder();
}
 
Example 5
Project: de.flapdoodle.solid   File: Blobs.java   Source Code and License 6 votes vote down vote up
public static ImmutableMultimap<String, Object> pathPropertiesOfAsMultimap(Blob blob, Function<String, Collection<String>> pathPropertyMapping, Path path, PropertyCollectionResolver propertyResolver) {
	ImmutableList<String> pathProperties = path.propertyNamesWithoutPage();
	
	ImmutableMap<String, ImmutableSet<?>> blopPathPropertyMap = pathProperties.stream()
		.map(p -> Pair.<String, ImmutableSet<?>>of(p, propertyOf(blob, pathPropertyMapping, propertyResolver, p)))
		.filter(pair -> !pair.b().isEmpty())
		.collect(ImmutableMap.toImmutableMap(Pair::a, Pair::b));
	
	if (blopPathPropertyMap.keySet().size()<pathProperties.size()) {
		return ImmutableMultimap.of();
	}
	
	Builder<String, Object> multiMapBuilder = ImmutableMultimap.builder();
	
	blopPathPropertyMap.forEach((key, values) -> {
		multiMapBuilder.putAll(key, values);
	});
	
	return multiMapBuilder.build();
}
 
Example 6
Project: de.flapdoodle.solid   File: ImmutableGroupedPropertyMap.java   Source Code and License 6 votes vote down vote up
public ImmutableGroupedPropertyMap build() {
	ImmutableMap.Builder<Key, ImmutableMap<String, Object>> mapOfMapsBuilder=ImmutableMap.builder();
	ImmutableMultimap.Builder<Key, String> groupOfKeyBuilder=ImmutableMultimap.builder();
	
	maps.forEach((key, map) -> {
		mapOfMapsBuilder.put(key, ImmutableMap.copyOf(map));
	});
	
	maps.keySet().forEach(key -> {
		Key current=key;
		while (!current.isRoot()) {
			Key parent = current.parent();
			groupOfKeyBuilder.put(parent, current.last());
			current=parent;
		}
	});
	
	return new ImmutableGroupedPropertyMap(mapOfMapsBuilder.build(), groupOfKeyBuilder.build());
}
 
Example 7
Project: tac-kbp-eal   File: EAScoringObserver.java   Source Code and License 6 votes vote down vote up
private ImmutableMultimap<String, FMeasureCounts> toFMeasures(
    Collection<BrokenDownSummaryConfusionMatrix<Symbol>> data,
    Map.Entry<String, Collection<Symbol>> FMeasureSymbol) {
  final ImmutableMultimap.Builder<String, FMeasureCounts> ret = ImmutableMultimap.builder();

    /*
     MapUtils.copyWithTransformedEntries(data.asMap(),
                        Functions.toStringFunction(), FmeasureVs(FMeasureSymbol.getValue()));
     */
  final Function<SummaryConfusionMatrix, FMeasureCounts> scoringFunction =
      FmeasureVs(ImmutableSet.copyOf(FMeasureSymbol.getValue()));
  for (final BrokenDownSummaryConfusionMatrix<Symbol> dataPoint : data) {
    for (final Map.Entry<Symbol, SummaryConfusionMatrix> entry : dataPoint.asMap().entrySet()) {
      ret.put(entry.getKey().toString(), scoringFunction.apply(entry.getValue()));
    }
  }

  return ret.build();
}
 
Example 8
Project: stroom-stats   File: StopProcessingTask.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(final ImmutableMultimap<String, String> parameters, final PrintWriter output) throws Exception {

    LOGGER.info("{} endpoint called", TASK_NAME);

    @SuppressWarnings("FutureReturnValueIgnored")
    Future<Void> future = CompletableFuture
            .runAsync(statisticsIngestService::stop)
            .handle((aVoid, ex) -> {
                if (ex != null) {
                    LOGGER.error("Task {} failed with error {}", TASK_NAME, ex.getMessage(), ex);
                } else {
                    LOGGER.info("Task {} completed successfully", TASK_NAME);
                }
                return aVoid;
            });
}
 
Example 9
Project: de.flapdoodle.solid   File: Menu.java   Source Code and License 6 votes vote down vote up
public static ImmutableList<Menu> of(ImmutableMultimap<ImmutableMap<String, Object>, Blob> groupedBlobs) {
	ImmutableList<BlobAndMenu> sortedBlobs = groupedBlobs.inverse().asMap()
			.entrySet()
			.stream()
			.filter(e -> !e.getValue().isEmpty())
			.map(e -> BlobAndMenu.of(e.getKey(), e.getValue().iterator().next()))
			.sorted((a,b) -> Long.compare(a.menu().weight(), b.menu().weight()))
			.collect(ImmutableList.toImmutableList());
	
	ImmutableList<BlobAndMenu> parents = sortedBlobs.stream()
			.filter(blobmenu -> !blobmenu.menu().parent().isPresent())
			.collect(ImmutableList.toImmutableList());
	
	return parents.stream()
		.map(parent -> asMenu(parent,sortedBlobs))
		.collect(ImmutableList.toImmutableList());
}
 
Example 10
Project: ProjectAres   File: MapUtils.java   Source Code and License 6 votes vote down vote up
public static <K, V> Multimap<K, V> combine(Iterable<Multimap<K, V>> maps) {
    Multimap<K, V> singleton = null;
    ImmutableMultimap.Builder<K, V> builder = null;
    for(Multimap<K, V> map : maps) {
        if(!map.isEmpty()) {
            if(singleton == null) {
                singleton = map;
            } else {
                if(builder == null) {
                    builder = ImmutableMultimap.builder();
                }
                builder.putAll(singleton);
                builder.putAll(map);
            }
        }
    }

    if(builder != null) {
        return builder.build();
    } else if(singleton != null) {
        return singleton;
    } else {
        return ImmutableMultimap.of();
    }
}
 
Example 11
Project: de.flapdoodle.solid   File: Collectors.java   Source Code and License 6 votes vote down vote up
public static <T, L, K> Collector<T, ?, ImmutableMultimap<K, T>> groupingByValues(Function<? super T, ? extends Iterable<? extends K>> classifier) {
	return ImmutableGenericCollector.<T, LinkedListMultimap<K, T>, ImmutableMultimap<K, T>>builder()
		.supplier(LinkedListMultimap::create)
		.accumulator((map, t) -> {
			classifier.apply(t).forEach(k -> {
				map.put(k, t);
			});
		})
		.combiner((a,b) -> {
			LinkedListMultimap<K, T> ret = LinkedListMultimap.create(a);
			ret.putAll(b);
			return ret;
		})
		.finisher(map -> ImmutableMultimap.copyOf(map))
		.build();
}
 
Example 12
Project: Equella   File: ItemDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Transactional(propagation = Propagation.MANDATORY)
public Multimap<Long, String> getCollaboratorsForItemIds(Collection<Long> itemIds)
{
	if( itemIds.isEmpty() )
	{
		return ImmutableMultimap.of();
	}
	List<Object[]> attachments = getHibernateTemplate().findByNamedParam(
		"select c, i.id from Item i join i.collaborators c where i.id in (:items)", "items", itemIds);
	ListMultimap<Long, String> multiMap = ArrayListMultimap.create();
	for( Object[] attachmentRow : attachments )
	{
		multiMap.put((Long) attachmentRow[1], (String) attachmentRow[0]);
	}
	return multiMap;
}
 
Example 13
Project: javaide   File: Actions.java   Source Code and License 6 votes vote down vote up
public ImmutableMultimap<Integer, Record> getResultingSourceMapping(XmlDocument xmlDocument)
        throws ParserConfigurationException, SAXException, IOException {

    XmlLoader.SourceLocation inMemory = XmlLoader.UNKNOWN;

    XmlDocument loadedWithLineNumbers = XmlLoader.load(
            xmlDocument.getSelectors(),
            xmlDocument.getSystemPropertyResolver(),
            inMemory,
            xmlDocument.prettyPrint(),
            XmlDocument.Type.MAIN,
            Optional.<String>absent() /* mainManifestPackageName */);

    ImmutableMultimap.Builder<Integer, Record> mappingBuilder = ImmutableMultimap.builder();
    for (XmlElement xmlElement : loadedWithLineNumbers.getRootNode().getMergeableElements()) {
        parse(xmlElement, mappingBuilder);
    }
    return mappingBuilder.build();
}
 
Example 14
Project: javaide   File: Actions.java   Source Code and License 6 votes vote down vote up
private void parse(XmlElement element,
        ImmutableMultimap.Builder<Integer, Record> mappings) {
    DecisionTreeRecord decisionTreeRecord = mRecords.get(element.getId());
    if (decisionTreeRecord != null) {
        NodeRecord nodeRecord = findNodeRecord(decisionTreeRecord);
        if (nodeRecord != null) {
            mappings.put(element.getPosition().getLine(), nodeRecord);
        }
        for (XmlAttribute xmlAttribute : element.getAttributes()) {
            AttributeRecord attributeRecord = findAttributeRecord(decisionTreeRecord,
                    xmlAttribute);
            if (attributeRecord != null) {
                mappings.put(xmlAttribute.getPosition().getLine(), attributeRecord);
            }
        }
    }
    for (XmlElement xmlElement : element.getMergeableElements()) {
        parse(xmlElement, mappings);
    }
}
 
Example 15
Project: javaide   File: Actions.java   Source Code and License 6 votes vote down vote up
public String blame(XmlDocument xmlDocument)
        throws IOException, SAXException, ParserConfigurationException {

    ImmutableMultimap<Integer, Record> resultingSourceMapping =
            getResultingSourceMapping(xmlDocument);
    LineReader lineReader = new LineReader(
            new StringReader(xmlDocument.prettyPrint()));

    StringBuilder actualMappings = new StringBuilder();
    String line;
    int count = 1;
    while ((line = lineReader.readLine()) != null) {
        actualMappings.append(count).append(line).append("\n");
        if (resultingSourceMapping.containsKey(count)) {
            for (Record record : resultingSourceMapping.get(count)) {
                actualMappings.append(count).append("-->")
                        .append(record.getActionLocation().toString())
                        .append("\n");
            }
        }
        count++;
    }
    return actualMappings.toString();
}
 
Example 16
Project: hashsdn-controller   File: DOMNotificationRouter.java   Source Code and License 6 votes vote down vote up
@Override
public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(final T listener, final Collection<SchemaPath> types) {
    final ListenerRegistration<T> reg = new AbstractListenerRegistration<T>(listener) {
        @Override
        protected void removeRegistration() {
            final ListenerRegistration<T> me = this;

            synchronized (DOMNotificationRouter.this) {
                replaceListeners(ImmutableMultimap.copyOf(Multimaps.filterValues(listeners, input -> input != me)));
            }
        }
    };

    if (!types.isEmpty()) {
        final Builder<SchemaPath, ListenerRegistration<? extends DOMNotificationListener>> b = ImmutableMultimap.builder();
        b.putAll(listeners);

        for (final SchemaPath t : types) {
            b.put(t, reg);
        }

        replaceListeners(b.build());
    }

    return reg;
}
 
Example 17
Project: OperatieBRP   File: MetaObject.java   Source Code and License 6 votes vote down vote up
/**
 * Bouwt het MetaObject.
 * @param parentObject het parent meta object
 * @return het MetaObject
 */
MetaObject build(final MetaObject parentObject) {
    final MetaObject gebouwdObject = new MetaObject();
    gebouwdObject.parentObject = parentObject;
    gebouwdObject.objectsleutel = objectsleutel;
    gebouwdObject.objectElement = objectElement;

    final Multimap<ObjectElement, MetaObject> tempObjectenMap = HashMultimap.create();
    for (final Builder builder : objectBuilderList) {
        final MetaObject object = builder.build(gebouwdObject);
        tempObjectenMap.put(object.getObjectElement(), object);
    }
    gebouwdObject.elementObjectMap = ImmutableMultimap.copyOf(tempObjectenMap);
    gebouwdObject.objecten = ImmutableSet.copyOf(tempObjectenMap.values());

    final Map<GroepElement, MetaGroep> tempGroepenMap = Maps.newHashMap();
    for (final MetaGroep.Builder groepBuilder : groepBuilderList) {
        final MetaGroep groep = groepBuilder.build(gebouwdObject);
        tempGroepenMap.put(groep.getGroepElement(), groep);
    }
    gebouwdObject.elementGroepMap = ImmutableMap.copyOf(tempGroepenMap);
    gebouwdObject.groepen = ImmutableSet.copyOf(tempGroepenMap.values());
    return gebouwdObject;
}
 
Example 18
Project: de.flapdoodle.solid   File: Blobs.java   Source Code and License 5 votes vote down vote up
public static ImmutableMultimap<ImmutableMap<String, Object>, Blob> orderByKey(ImmutableMultimap<ImmutableMap<String, Object>, Blob> src,
		ImmutableList<String> pathOrdering) {
	ImmutableMultimap.Builder<ImmutableMap<String, Object>, Blob> builder=ImmutableMultimap.builder();
	
	src.asMap().entrySet()
		.stream()
		.sorted(pathOrderingOf(pathOrdering))
		.forEach(e -> {
			builder.putAll(e.getKey(), e.getValue());
		});
	
	return builder.build();
}
 
Example 19
Project: de.flapdoodle.solid   File: Collectors.java   Source Code and License 5 votes vote down vote up
public static <T, K> Collector<T, ?, ImmutableMultimap<K, T>> groupingBy(Function<? super T, ? extends K> classifier) {
	return ImmutableGenericCollector.<T, LinkedListMultimap<K, T>, ImmutableMultimap<K, T>>builder()
		.supplier(LinkedListMultimap::create)
		.accumulator((map, t) -> {
			map.put(classifier.apply(t), t);
		})
		.combiner((a,b) -> {
			LinkedListMultimap<K, T> ret = LinkedListMultimap.create(a);
			ret.putAll(b);
			return ret;
		})
		.finisher(map -> ImmutableMultimap.copyOf(map))
		.build();
}
 
Example 20
Project: mug   File: BiStreamTest.java   Source Code and License 5 votes vote down vote up
@Test public void testMapKeys() {
  assertKeyValues(BiStream.of("one", 1).mapKeys((k, v) -> k + v))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one1", 1))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1).mapKeys(k -> k + k))
      .containsExactlyEntriesIn(ImmutableMultimap.of("oneone", 1))
      .inOrder();
}
 
Example 21
Project: mug   File: BiStreamTest.java   Source Code and License 5 votes vote down vote up
@Test public void testMapValues() {
  assertKeyValues(BiStream.of("one", 1).mapValues((k, v) -> k + v))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", "one1"))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1).mapValues(v -> v * 10))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 10))
      .inOrder();
}
 
Example 22
Project: de.flapdoodle.solid   File: MultimapsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void flattenSampleWith3() {
	ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
			.putAll("a", 1,4)
			.putAll("m", 0)
			.putAll("b", 2,3)
			.build());
	
	assertEquals(4,result.size());
	assertEquals("[{a=1, m=0, b=2}, {a=4, m=0, b=2}, {a=1, m=0, b=3}, {a=4, m=0, b=3}]",result.toString());
}
 
Example 23
Project: mug   File: BiStreamTest.java   Source Code and License 5 votes vote down vote up
@Test public void testFlatMapValues() {
  assertKeyValues(BiStream.of("one", 1).flatMapValues((k, v) -> Stream.of(k, v)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", "one", "one", 1))
      .inOrder();
  assertKeyValues(BiStream.of("one", 1).flatMapValues(v -> Stream.of(v, v * 10)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1, "one", 10))
      .inOrder();
}
 
Example 24
Project: de.flapdoodle.solid   File: DefaultSiteGenerator.java   Source Code and License 5 votes vote down vote up
private ImmutableMultimap<ImmutableMap<String, Object>, Blob> reverse(ImmutableMultimap<ImmutableMap<String, Object>, Blob> src) {
	ImmutableMultimap.Builder<ImmutableMap<String,Object>, Blob> builder=ImmutableMultimap.builder();
	src.keySet().asList().reverse().forEach(key -> {
		builder.putAll(key, src.get(key));
	});
	return builder.build();
}
 
Example 25
Project: mug   File: BiStreamTest.java   Source Code and License 5 votes vote down vote up
@Test public void testPeek() {
  AtomicInteger sum = new AtomicInteger();
  assertKeyValues(BiStream.of(1, 2, 3, 4).peek((k, v) -> sum.addAndGet(k + v)))
      .containsExactlyEntriesIn(ImmutableMultimap.of(1, 2, 3, 4))
      .inOrder();
  assertThat(sum.get()).isEqualTo(10);
}
 
Example 26
Project: mug   File: BiStreamTest.java   Source Code and License 5 votes vote down vote up
@Test public void testSorted() {
  assertKeyValues(
          BiStream.of("b", 10, "a", 11, "a", 22)
              .sorted(Comparator.naturalOrder(), Comparator.naturalOrder()))
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 11, "a", 22, "b", 10))
      .inOrder();
}
 
Example 27
Project: de.flapdoodle.solid   File: MultimapsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void flattenSampleWithOneCollection() {
	ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
			.putAll("a", 1)
			.putAll("b", 2,3)
			.build());
	
	assertEquals(2,result.size());
	assertEquals("[{a=1, b=2}, {a=1, b=3}]",result.toString());
}
 
Example 28
Project: mug   File: BiStreamTest.java   Source Code and License 5 votes vote down vote up
@Test public void toBiCollectionWithCollectorStrategy() {
  BiCollection<String, Integer> biCollection = BiStream.of("a", 1)
      .toBiCollection(ImmutableList::toImmutableList);
  assertKeyValues(biCollection.stream())
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1))
      .inOrder();
  assertKeyValues(biCollection.stream())
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1))
      .inOrder();
}
 
Example 29
Project: tac-kbp-eal   File: SelectForDualAnnotation.java   Source Code and License 5 votes vote down vote up
private static ImmutableMultimap<Symbol, Symbol> makeAnnotatorsToDocumentsMap(
    Table<Symbol, Symbol, Symbol> annotatorsTable, Set<Symbol> targetDocIDs) {
  final ImmutableMultimap.Builder<Symbol, Symbol> ret = ImmutableMultimap.builder();

  for (final Symbol docID : targetDocIDs) {
    for (final Symbol annotator : annotatorsTable.row(docID).values()) {
      ret.put(annotator, docID);
    }
  }

  return ret.build();
}
 
Example 30
Project: tac-kbp-eal   File: SelectForDualAnnotation.java   Source Code and License 5 votes vote down vote up
private static ImmutableMultimap<Symbol, Symbol> makeEventTypesToDocumentsMap(
    AnnotationStore annotationStore, Set<Symbol> targetDocIDs) throws IOException {
  final ImmutableMultimap.Builder<Symbol, Symbol> ret = ImmutableMultimap.builder();

  for (final Symbol docID : targetDocIDs) {
    for (final Response response : annotationStore.readOrEmpty(docID).allResponses()) {
      ret.put(response.type(), docID);
    }
  }

  return ret.build();
}
 
Example 31
Project: tac-kbp-eal   File: FilterAnswerKeyByTypeAndRole.java   Source Code and License 5 votes vote down vote up
private static Multimap<Symbol, Symbol> loadTypesToValidRolesMap(final Parameters params)
    throws IOException {
  final Multimap<Symbol, Symbol> typesToValidRolesInitial = FileUtils.loadSymbolMultimap(
      Files.asCharSource(params.getExistingFile("typeAndRoleFile"), Charsets.UTF_8));
  final Set<Symbol> alwaysValidRoles = params.getSymbolSet("alwaysValidRoles");
  final ImmutableMultimap.Builder<Symbol, Symbol> typesToValidRolesB = ImmutableMultimap.builder();
  typesToValidRolesB.putAll(typesToValidRolesInitial);
  for (final Symbol eventType : typesToValidRolesInitial.keySet()) {
    typesToValidRolesB.putAll(eventType, alwaysValidRoles);
  }
  return typesToValidRolesB.build();
}
 
Example 32
Project: tac-kbp-eal   File: _CorpusEventLinking.java   Source Code and License 5 votes vote down vote up
@Value.Derived
public ImmutableMultimap<DocEventFrameReference, CorpusEventFrame> docEventsToCorpusEvents() {
  final ImmutableMultimap.Builder<DocEventFrameReference, CorpusEventFrame> ret =
      ImmutableMultimap.builder();

  for (final CorpusEventFrame corpusEventFrame : corpusEventFrames()) {
    for (final DocEventFrameReference docEventFrameReference : corpusEventFrame
        .docEventFrames()) {
      ret.put(docEventFrameReference, corpusEventFrame);
    }
  }

  return ret.build();
}
 
Example 33
Project: tac-kbp-eal   File: CorefAnnotation.java   Source Code and License 5 votes vote down vote up
private CorefAnnotation(final Symbol docId, final Multimap<Integer, KBPString> idToCASes,
    final Map<KBPString, Integer> CASesToIDs, final Set<KBPString> unannotated) {
  this.docId = checkNotNull(docId);
  this.idToCASes = ImmutableMultimap.copyOf(idToCASes);
  this.CASesToIDs = ImmutableMap.copyOf(CASesToIDs);
  this.unannotated = ImmutableSet.copyOf(unannotated);
  checkConsistency();
}
 
Example 34
Project: tac-kbp-eal   File: ExactMatchEventArgumentLinkingAligner.java   Source Code and License 5 votes vote down vote up
/**
 * Converts a {@link ResponseLinking} to an {@link EventArgumentLinking} using a {@link
 * CorefAnnotation} from an {@link com.bbn.kbp.events2014.AnswerKey} to canonicalize the
 * responses.  If the canonicalization is inconsistent with the response linking, an {@link
 * java.lang.IllegalArgumentException} will be thrown.
 */
public EventArgumentLinking align(ResponseLinking responseLinking,
    AnswerKey answerKey)  {
  checkArgument(answerKey.docId() == responseLinking.docID());

  // assertLinkingSubsetOfAnswerKey(responseLinking, answerKey);
  // the above assertion was too strong - the system response linking could
  // validly include responses which were not included in the answerKey because
  // there was a higher scoring system response in the same equivalence class

  final ImmutableMultimap<TypeRoleFillerRealis, Response> canonicalToResponses =
      Multimaps.index(responseLinking.allResponses(),
          TypeRoleFillerRealis.extractFromSystemResponse(
              answerKey.corefAnnotation().strictCASNormalizerFunction()));

  final Multimap<Response, TypeRoleFillerRealis> responsesToCanonical =
      canonicalToResponses.inverse();

  final ImmutableSet.Builder<TypeRoleFillerRealisSet> coreffedArgs = ImmutableSet.builder();
  for (final ResponseSet responseSet : responseLinking.responseSets()) {
    coreffedArgs.add(TypeRoleFillerRealisSet.from(
        canonicalizeResponseSet(responseSet.asSet(),
            canonicalToResponses, responsesToCanonical)));
  }
  final ImmutableSet<TypeRoleFillerRealis> incompleteResponses = canonicalizeResponseSet(
      responseLinking.incompleteResponses(), canonicalToResponses, responsesToCanonical);

  return EventArgumentLinking.builder().docID(responseLinking.docID())
      .eventFrames(coreffedArgs.build()).incomplete(incompleteResponses).build();
}
 
Example 35
Project: tac-kbp-eal   File: ExactMatchEventArgumentLinkingAligner.java   Source Code and License 5 votes vote down vote up
@Override
public ResponseLinking alignToResponseLinking(EventArgumentLinking eventArgumentLinking,
    AnswerKey answerKey) {
  // For every Response in answerKey, answerKey.corefAnnotation().strictCASNormalizerFunction() will try to find
  // a canonical coreferent for the Response's CAS (KBPString), by checking CorefAnnotation.CASesToIDs
  // If the KBPString does not exist in CASesToIDs, then an Exception will be thrown
  final ImmutableMultimap<TypeRoleFillerRealis, Response> canonicalToResponses =
      Multimaps.index(answerKey.allResponses(),
          TypeRoleFillerRealis.extractFromSystemResponse(
              answerKey.corefAnnotation().strictCASNormalizerFunction()));

  final ImmutableSet.Builder<Response> incompletes = ImmutableSet.builder();
  for (final TypeRoleFillerRealis incompleteEquivClass : eventArgumentLinking.incomplete()) {
    incompletes.addAll(canonicalToResponses.get(incompleteEquivClass));
  }

  final ImmutableSet.Builder<ResponseSet> responseSets = ImmutableSet.builder();
  for (final TypeRoleFillerRealisSet equivClassSet : eventArgumentLinking.eventFrames()) {
    final ImmutableSet.Builder<Response> setBuilder = ImmutableSet.builder();
    for (final TypeRoleFillerRealis trfr : equivClassSet.asSet()) {
      setBuilder.addAll(canonicalToResponses.get(trfr));
    }
    responseSets.add(ResponseSet.from(setBuilder.build()));
  }

  return ResponseLinking.builder().docID(answerKey.docId()).responseSets(responseSets.build())
      .incompleteResponses(incompletes.build()).build();
}
 
Example 36
Project: tac-kbp-eal   File: SingleFileQueryAssessmentsLoader.java   Source Code and License 5 votes vote down vote up
public final CorpusQueryAssessments loadFrom(final CharSource source) throws IOException {
  final List<String> lines = source.readLines();
  final List<QueryResponse2016> queries = Lists.newArrayList();
  final Map<QueryResponse2016, String> metadata = Maps.newHashMap();
  final ImmutableMultimap.Builder<QueryResponse2016, Symbol> responsesToSystems =
      ImmutableMultimap.builder();
  final Map<QueryResponse2016, QueryAssessment2016> assessments = Maps.newHashMap();
  Optional<String> lastMetadata = Optional.absent();
  for (final String line : lines) {
    if (line.startsWith("#")) {
      lastMetadata = Optional.of(line.trim().substring(1));
    } else {
      final String[] parts = line.trim().split("\t");
      checkArgument(parts.length == 5, "expected five columns, but got " + parts.length);
      final Symbol queryID = Symbol.from(parts[0]);
      final Symbol docID = Symbol.from(parts[1]);
      final String[] systemIDs = parts[2].split(",");
      final ImmutableSortedSet<CharOffsetSpan> spans = extractPJSpans(parts[3]);
      final QueryAssessment2016 assessment = QueryAssessment2016.valueOf(parts[4]);
      final QueryResponse2016 query =
          QueryResponse2016.builder().queryID(queryID).docID(docID)
              .addAllPredicateJustifications(spans).build();
      queries.add(query);
      for(final String systemID: systemIDs) {
        responsesToSystems.put(query, Symbol.from(systemID));
      }
      if (!assessment.equals(QueryAssessment2016.UNASSESSED)) {
        assessments.put(query, assessment);
      }
      if (lastMetadata.isPresent()) {
        metadata.put(query, lastMetadata.get());
        lastMetadata = Optional.absent();
      }
    }
  }
  return CorpusQueryAssessments.builder().addAllQueryReponses(queries).assessments(assessments)
      .queryResponsesToSystemIDs(responsesToSystems.build())
      .metadata(metadata).build();
}
 
Example 37
Project: tac-kbp-eal   File: AnswerAlignment.java   Source Code and License 5 votes vote down vote up
private AnswerAlignment(
    final Multimap<Answerable, LeftAnswer> equivalenceClassesToLeftItems,
    final Multimap<Answerable, RightAnswer> equivalenceClassesToRightItems) {
  this.ecToLeft = ImmutableMultimap.copyOf(equivalenceClassesToLeftItems);
  this.ecToRight = ImmutableMultimap.copyOf(equivalenceClassesToRightItems);

  // build set of equivalence classes
  final ImmutableSet.Builder<Answerable> classesBuilder = ImmutableSet.builder();
  classesBuilder.addAll(equivalenceClassesToLeftItems.keySet());
  classesBuilder.addAll(equivalenceClassesToRightItems.keySet());
  this.answerables = classesBuilder.build();
}
 
Example 38
Project: de.flapdoodle.solid   File: MultimapsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void flattenSampleWithTwoCollections() {
	ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
			.putAll("a", 1,4)
			.putAll("b", 2,3)
			.build());
	
	assertEquals(4,result.size());
	assertEquals("[{a=1, b=2}, {a=4, b=2}, {a=1, b=3}, {a=4, b=3}]",result.toString());
}
 
Example 39
Project: tac-kbp-eal   File: EAScoringObserver.java   Source Code and License 5 votes vote down vote up
@MoveToBUECommon
private static <K, V> ImmutableMultimap<K, V> combineMapsToMultimap(
    Iterable<? extends Map<K, V>> maps) {
  final ImmutableMultimap.Builder<K, V> ret = ImmutableMultimap.builder();

  for (final Map<K, V> map : maps) {
    ret.putAll(Multimaps.forMap(map));
  }

  return ret.build();
}
 
Example 40
Project: de.flapdoodle.solid   File: MultimapsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void flattenSimpleSample() {
	ImmutableList<ImmutableMap<String, Integer>> result = Multimaps.flatten(ImmutableMultimap.<String, Integer>builder()
			.putAll("a", 1)
			.putAll("b", 2)
			.build());
	
	assertEquals(1,result.size());
	assertEquals("[{a=1, b=2}]",result.toString());
}
 
Example 41
Project: guava-mock   File: ServiceManager.java   Source Code and License 5 votes vote down vote up
ImmutableMultimap<State, Service> servicesByState() {
  ImmutableSetMultimap.Builder<State, Service> builder = ImmutableSetMultimap.builder();
  monitor.enter();
  try {
    for (Entry<State, Service> entry : servicesByState.entries()) {
      if (!(entry.getValue() instanceof NoOpService)) {
        builder.put(entry);
      }
    }
  } finally {
    monitor.leave();
  }
  return builder.build();
}
 
Example 42
Project: guava-mock   File: NullPointerTesterTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unused") // called by NullPointerTester
public void checkDefaultValuesForTheseTypes(
    Gender gender,
    Integer integer, int i,
    String string, CharSequence charSequence,
    List<String> list,
    ImmutableList<Integer> immutableList,
    Map<String, Integer> map,
    ImmutableMap<String, String> immutableMap,
    Set<String> set,
    ImmutableSet<Integer> immutableSet,
    SortedSet<Number> sortedSet,
    ImmutableSortedSet<Number> immutableSortedSet,
    Multiset<String> multiset,
    ImmutableMultiset<Integer> immutableMultiset,
    Multimap<String, Integer> multimap,
    ImmutableMultimap<String, Integer> immutableMultimap,
    Table<String, Integer, Exception> table,
    ImmutableTable<Integer, String, Exception> immutableTable) {
  calledWith(
      gender,
      integer, i,
      string, charSequence,
      list, immutableList,
      map, immutableMap,
      set, immutableSet,
      sortedSet, immutableSortedSet,
      multiset, immutableMultiset,
      multimap, immutableMultimap,
      table, immutableTable);
}
 
Example 43
Project: guava-mock   File: NullPointerTesterTest.java   Source Code and License 5 votes vote down vote up
final void check() {
  runTester().assertNonNullValues(
      Gender.MALE,
      Integer.valueOf(0), 0,
      "", "",
      ImmutableList.of(), ImmutableList.of(),
      ImmutableMap.of(), ImmutableMap.of(),
      ImmutableSet.of(), ImmutableSet.of(),
      ImmutableSortedSet.of(), ImmutableSortedSet.of(),
      ImmutableMultiset.of(), ImmutableMultiset.of(),
      ImmutableMultimap.of(), ImmutableMultimap.of(),
      ImmutableTable.of(), ImmutableTable.of());
}
 
Example 44
Project: guava-mock   File: MediaTypeTest.java   Source Code and License 5 votes vote down vote up
public void testEquals() {
  new EqualsTester()
      .addEqualityGroup(
          MediaType.create("text", "plain"),
          MediaType.create("TEXT", "PLAIN"),
          MediaType.parse("text/plain"),
          MediaType.parse("TEXT/PLAIN"),
          MediaType.create("text", "plain").withParameter("a", "1").withoutParameters())
      .addEqualityGroup(
          MediaType.create("text", "plain").withCharset(UTF_8),
          MediaType.create("text", "plain").withParameter("CHARSET", "UTF-8"),
          MediaType.create("text", "plain")
              .withParameters(ImmutableMultimap.of("charset", "utf-8")),
          MediaType.parse("text/plain;charset=utf-8"),
          MediaType.parse("text/plain; charset=utf-8"),
          MediaType.parse("text/plain;  charset=utf-8"),
          MediaType.parse("text/plain; \tcharset=utf-8"),
          MediaType.parse("text/plain; \r\n\tcharset=utf-8"),
          MediaType.parse("text/plain; CHARSET=utf-8"),
          MediaType.parse("text/plain; charset=\"utf-8\""),
          MediaType.parse("text/plain; charset=\"\\u\\tf-\\8\""),
          MediaType.parse("text/plain; charset=UTF-8"),
          MediaType.parse("text/plain ; charset=utf-8"))
      .addEqualityGroup(MediaType.parse("text/plain; charset=utf-8; charset=utf-8"))
      .addEqualityGroup(
          MediaType.create("text", "plain").withParameter("a", "value"),
          MediaType.create("text", "plain").withParameter("A", "value"))
      .addEqualityGroup(
          MediaType.create("text", "plain").withParameter("a", "VALUE"),
          MediaType.create("text", "plain").withParameter("A", "VALUE"))
      .addEqualityGroup(
          MediaType.create("text", "plain")
              .withParameters(ImmutableListMultimap.of("a", "1", "a", "2")),
          MediaType.create("text", "plain")
              .withParameters(ImmutableListMultimap.of("a", "2", "a", "1")))
      .addEqualityGroup(MediaType.create("text", "csv"))
      .addEqualityGroup(MediaType.create("application", "atom+xml"))
      .testEquals();
}
 
Example 45
Project: creacoinj   File: StoredPaymentChannelClientStates.java   Source Code and License 5 votes vote down vote up
/**
 * Get a copy of all {@link StoredClientChannel}s
 */
public Multimap<Sha256Hash, StoredClientChannel> getChannelMap() {
    lock.lock();
    try {
        return ImmutableMultimap.copyOf(mapChannels);
    } finally {
        lock.unlock();
    }
}
 
Example 46
Project: Equella   File: InstitutionGlobalTask.java   Source Code and License 5 votes vote down vote up
private void updateSingleInst(long schemaId, Institution institution)
{
	removeInstitution(institution.getUniqueId());
	addInstitution(createStatus(institution, schemaId));
	TransientListStatusChange changer = new TransientListStatusChange(KEY_EVENTS);
	changer.add(new InstitutionEvent(InstitutionEvent.InstitutionEventType.EDITED, ImmutableMultimap.of(schemaId, institution)));
	mergeChanges(changer);
}
 
Example 47
Project: VirtualChest   File: VirtualChestInventory.java   Source Code and License 5 votes vote down vote up
VirtualChestInventory(VirtualChestPlugin plugin, VirtualChestInventoryBuilder builder)
{
    this.plugin = plugin;
    this.logger = plugin.getLogger();
    this.actionIntervalManager = plugin.getActionIntervalManager();

    this.title = builder.title;
    this.height = builder.height;
    this.triggerItem = builder.triggerItem;
    this.openActionCommand = builder.openActionCommand;
    this.closeActionCommand = builder.closeActionCommand;
    this.updateIntervalTick = builder.updateIntervalTick;
    this.items = ImmutableMultimap.copyOf(builder.items);
    this.acceptableActionIntervalTick = builder.actionIntervalTick.map(OptionalInt::of).orElse(OptionalInt.empty());
}
 
Example 48
Project: okwallet   File: StoredPaymentChannelClientStates.java   Source Code and License 5 votes vote down vote up
/**
 * Get a copy of all {@link StoredClientChannel}s
 */
public Multimap<Sha256Hash, StoredClientChannel> getChannelMap() {
    lock.lock();
    try {
        return ImmutableMultimap.copyOf(mapChannels);
    } finally {
        lock.unlock();
    }
}
 
Example 49
Project: googles-monorepo-demo   File: NullPointerTesterTest.java   Source Code and License 5 votes vote down vote up
final void check() {
  runTester().assertNonNullValues(
      Gender.MALE,
      Integer.valueOf(0), 0,
      "", "",
      ImmutableList.of(), ImmutableList.of(),
      ImmutableMap.of(), ImmutableMap.of(),
      ImmutableSet.of(), ImmutableSet.of(),
      ImmutableSortedSet.of(), ImmutableSortedSet.of(),
      ImmutableMultiset.of(), ImmutableMultiset.of(),
      ImmutableMultimap.of(), ImmutableMultimap.of(),
      ImmutableTable.of(), ImmutableTable.of());
}
 
Example 50
Project: googles-monorepo-demo   File: MediaTypeTest.java   Source Code and License 5 votes vote down vote up
public void testEquals() {
  new EqualsTester()
      .addEqualityGroup(
          MediaType.create("text", "plain"),
          MediaType.create("TEXT", "PLAIN"),
          MediaType.parse("text/plain"),
          MediaType.parse("TEXT/PLAIN"),
          MediaType.create("text", "plain").withParameter("a", "1").withoutParameters())
      .addEqualityGroup(
          MediaType.create("text", "plain").withCharset(UTF_8),
          MediaType.create("text", "plain").withParameter("CHARSET", "UTF-8"),
          MediaType.create("text", "plain")
              .withParameters(ImmutableMultimap.of("charset", "utf-8")),
          MediaType.parse("text/plain;charset=utf-8"),
          MediaType.parse("text/plain; charset=utf-8"),
          MediaType.parse("text/plain;  charset=utf-8"),
          MediaType.parse("text/plain; \tcharset=utf-8"),
          MediaType.parse("text/plain; \r\n\tcharset=utf-8"),
          MediaType.parse("text/plain; CHARSET=utf-8"),
          MediaType.parse("text/plain; charset=\"utf-8\""),
          MediaType.parse("text/plain; charset=\"\\u\\tf-\\8\""),
          MediaType.parse("text/plain; charset=UTF-8"),
          MediaType.parse("text/plain ; charset=utf-8"))
      .addEqualityGroup(MediaType.parse("text/plain; charset=utf-8; charset=utf-8"))
      .addEqualityGroup(
          MediaType.create("text", "plain").withParameter("a", "value"),
          MediaType.create("text", "plain").withParameter("A", "value"))
      .addEqualityGroup(
          MediaType.create("text", "plain").withParameter("a", "VALUE"),
          MediaType.create("text", "plain").withParameter("A", "VALUE"))
      .addEqualityGroup(
          MediaType.create("text", "plain")
              .withParameters(ImmutableListMultimap.of("a", "1", "a", "2")),
          MediaType.create("text", "plain")
              .withParameters(ImmutableListMultimap.of("a", "2", "a", "1")))
      .addEqualityGroup(MediaType.create("text", "csv"))
      .addEqualityGroup(MediaType.create("application", "atom+xml"))
      .testEquals();
}
 
Example 51
Project: Re-Collector   File: CollectorServiceManager.java   Source Code and License 4 votes vote down vote up
public ImmutableMultimap<Service.State, Service> servicesByState() {
    return serviceManager.servicesByState();
}
 
Example 52
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testBiStream() {
  assertKeyValues(BiStream.biStream(Stream.of(1, 2)).mapKeys(Object::toString))
      .containsExactlyEntriesIn(ImmutableMultimap.of("1", 1, "2", 2))
      .inOrder();
}
 
Example 53
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testFlatMap2() {
  assertKeyValues(
      BiStream.of("one", 1).flatMap2((k, v) -> BiStream.of(k, v * 10, k, v * 11)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 10, "one", 11))
      .inOrder();
}
 
Example 54
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testFilterKeys() {
  assertKeyValues(BiStream.of("one", 1, "two", 2).filterKeys("one"::equals))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1))
      .inOrder();
}
 
Example 55
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testFilterValues() {
  assertKeyValues(BiStream.of("one", 1, "two", 2).filterValues(v -> v == 2))
      .containsExactlyEntriesIn(ImmutableMultimap.of("two", 2))
      .inOrder();
}
 
Example 56
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testCollect_toImmutableListMultimapWithInflexibleMapperTypes() {
  assertThat(BiStream.of("one", 1, "one", 10, "two", 2)
          .<ImmutableMultimap<String, Integer>>collect(BiStreamTest::toImmutableMultimap))
      .containsExactlyEntriesIn(ImmutableListMultimap.of("one", 1, "one", 10, "two", 2));
}
 
Example 57
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testZip_leftIsShorter() {
  assertKeyValues(BiStream.zip(Stream.of("a", "b"), Stream.of(1, 2, 3)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1, "b", 2));
}
 
Example 58
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testZip_rightIsShorter() {
  assertKeyValues(BiStream.zip(Stream.of("a", "b", "c"), Stream.of(1, 2)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1, "b", 2));
}
 
Example 59
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testZip_equalSize() {
  assertKeyValues(BiStream.zip(Stream.of("a", "b"), Stream.of(1, 2)))
      .containsExactlyEntriesIn(ImmutableMultimap.of("a", 1, "b", 2));
}
 
Example 60
Project: mug   File: BiStreamTest.java   Source Code and License 4 votes vote down vote up
@Test public void testLimit() {
  assertKeyValues(BiStream.of("one", 1, "two", 2, "three", 3).limit(2))
      .containsExactlyEntriesIn(ImmutableMultimap.of("one", 1, "two", 2))
      .inOrder();
}