Example usage for com.google.common.collect Multimaps index

List of usage examples for com.google.common.collect Multimaps index

Introduction

In this page you can find the example usage for com.google.common.collect Multimaps index.

Prototype

public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Creates an index ImmutableListMultimap that contains the results of applying a specified function to each item in an Iterator of values.

Usage

From source file:com.b2international.snowowl.snomed.core.ecl.SnomedEclRefinementEvaluator.java

/**
 * Evaluates partial results coming from a binary operator's left and right side within attribute group based refinements.
 * @param groupCardinality - the cardinality to check
 * @param groupOperator - the operator to use (AND or OR, aka {@link Sets#intersection(Set, Set)} or {@link Sets#union(Set, Set)})
 * @return a function that will can be chained via {@link Promise#then(Function)} to evaluate partial results when they are available
 *//*www  .  j  ava 2  s.  c om*/
private Function<List<Object>, Collection<Property>> evalParts(final Range<Long> groupCardinality,
        BinaryOperator<Set<Integer>> groupOperator) {
    return input -> {
        final Collection<Property> left = (Collection<Property>) input.get(0);
        final Collection<Property> right = (Collection<Property>) input.get(1);

        final Collection<Property> matchingAttributes = newHashSet();

        // group left and right side by source ID
        final Multimap<String, Property> leftRelationshipsBySource = Multimaps.index(left,
                Property::getObjectId);
        final Multimap<String, Property> rightRelationshipsBySource = Multimaps.index(right,
                Property::getObjectId);

        // check that each ID has the required number of groups with left and right relationships
        for (String sourceConcept : Iterables.concat(leftRelationshipsBySource.keySet(),
                rightRelationshipsBySource.keySet())) {
            final Multimap<Integer, Property> validGroups = ArrayListMultimap.create();

            final Collection<Property> leftSourceRelationships = leftRelationshipsBySource.get(sourceConcept);
            final Collection<Property> rightSourceRelationships = rightRelationshipsBySource.get(sourceConcept);

            final Multimap<Integer, Property> leftRelationshipsByGroup = Multimaps
                    .index(leftSourceRelationships, Property::getGroup);
            final Multimap<Integer, Property> rightRelationshipsByGroup = Multimaps
                    .index(rightSourceRelationships, Property::getGroup);

            for (Integer group : groupOperator.apply(leftRelationshipsByGroup.keySet(),
                    rightRelationshipsByGroup.keySet())) {
                validGroups.get(group).addAll(leftRelationshipsByGroup.get(group));
                validGroups.get(group).addAll(rightRelationshipsByGroup.get(group));
            }

            if (groupCardinality.contains((long) validGroups.keySet().size())) {
                matchingAttributes.addAll(validGroups.values());
            }
        }
        return matchingAttributes;
    };
}

From source file:org.eclipse.xtend.core.validation.XtendJavaValidator.java

@Check
public void checkMultipleAnnotations(final XtendAnnotationTarget annotationTarget) {
    if (annotationTarget.getAnnotations().size() <= 1 || !isRelevantAnnotationTarget(annotationTarget)) {
        return;// www .ja  va2  s.c o m
    }

    ImmutableListMultimap<String, XAnnotation> groupByIdentifier = Multimaps
            .index(annotationTarget.getAnnotations(), new Function<XAnnotation, String>() {
                public String apply(XAnnotation input) {
                    return input.getAnnotationType().getIdentifier();
                }
            });

    for (String qName : groupByIdentifier.keySet()) {
        ImmutableList<XAnnotation> sameType = groupByIdentifier.get(qName);
        if (sameType.size() > 1) {
            JvmType type = sameType.get(0).getAnnotationType();
            if (type instanceof JvmAnnotationType && !type.eIsProxy()
                    && !annotationLookup.isRepeatable((JvmAnnotationType) type)) {
                for (XAnnotation xAnnotation : sameType) {
                    error("Multiple annotations of non-repeatable type @"
                            + xAnnotation.getAnnotationType().getSimpleName()
                            + ". Only annotation types marked @Repeatable can be used multiple times at one target.",
                            xAnnotation, XAnnotationsPackage.Literals.XANNOTATION__ANNOTATION_TYPE,
                            INSIGNIFICANT_INDEX, ANNOTATION_MULTIPLE);
                }
            }
        }
    }
}

From source file:org.immutables.sequence.Sequence.java

/**
 * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
 * specified function to each item in this {@code Sequence} of values. Each element of this
 * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
 * size as this iterable. The key used to store that value in the multimap will be the result of
 * calling the function on that value. The resulting multimap is created as an immutable snapshot.
 * In the returned multimap, keys appear in the order they are first encountered, and the values
 * corresponding to each key appear in the same order as they are encountered.
 * @param <K> the key type//from   w  ww. j a  v a  2 s. c om
 * @param keyFunction the function used to produce the key for each value
 * @return the immutable list multimap
 * @since 14.0
 */
public final <K> ImmutableListMultimap<K, E> toMultimap(Function<? super E, K> keyFunction) {
    return Multimaps.index(iterable, keyFunction::apply);
}

From source file:dagger.internal.codegen.Key.java

/**
 * Indexes {@code haveKeys} by {@link HasKey#key()}.
 *//*from w  w w .  ja v a2  s .c  om*/
static <T extends HasKey> ImmutableSetMultimap<Key, T> indexByKey(Iterable<T> haveKeys) {
    return ImmutableSetMultimap.copyOf(Multimaps.index(haveKeys, HasKey::key));
}

From source file:edu.harvard.med.screensaver.service.libraries.PlateUpdater.java

private void updatePrimaryPlateLocation(Copy copy) {
    Set<Entry<PlateLocation, Integer>> plateLocationCounts = Maps
            .transformValues(Multimaps
                    .index(Iterables.filter(copy.getPlates().values(),
                            Predicates.compose(Predicates.notNull(), Plate.ToLocation)), Plate.ToLocation)
                    .asMap(), CollectionSize)
            .entrySet();//ww  w  .  j a v a2 s  .  c  o  m
    if (plateLocationCounts.isEmpty()) {
        copy.setPrimaryPlateLocation(null);
    } else {
        PlateLocation primaryPlateLocation = Collections
                .max(plateLocationCounts, plateLocationFrequencyComparator).getKey();
        copy.setPrimaryPlateLocation(primaryPlateLocation);
        copy.setPlateLocationsCount(plateLocationCounts.size());
    }
}

From source file:com.facebook.swift.codec.metadata.ThriftStructMetadataBuilder.java

private void normalizeThriftFields(ThriftCatalog catalog) {
    // assign all fields an id (if possible)
    Set<String> fieldsWithConflictingIds = inferThriftFieldIds();

    // group fields by id
    Multimap<Optional<Short>, FieldMetadata> fieldsById = Multimaps.index(fields, getThriftFieldId());
    for (Entry<Optional<Short>, Collection<FieldMetadata>> entry : fieldsById.asMap().entrySet()) {
        Collection<FieldMetadata> fields = entry.getValue();

        // fields must have an id
        if (!entry.getKey().isPresent()) {
            for (String fieldName : newTreeSet(transform(fields, getOrExtractThriftFieldName()))) {
                // only report errors for fields that don't have conflicting ids
                if (!fieldsWithConflictingIds.contains(fieldName)) {
                    metadataErrors.addError("ThriftStruct %s fields %s do not have an id", structName,
                            newTreeSet(transform(fields, getOrExtractThriftFieldName())));
                }//from  w ww . j  ava 2s .  co m
            }
            continue;
        }
        short fieldId = entry.getKey().get();

        // assure all fields for this ID have the same name
        String fieldName = extractFieldName(fieldId, fields);
        for (FieldMetadata field : fields) {
            field.setName(fieldName);
        }

        // verify fields have a supported java type and all fields
        // for this ID have the same thrift type
        verifyFieldType(fieldId, fieldName, fields, catalog);
    }
}

From source file:com.palantir.atlasdb.keyvalue.cassandra.CQLKeyValueService.java

private Map<byte[], List<Cell>> partitionCellsByPrimaryKey(Collection<Cell> cells) {
    return Multimaps.asMap(Multimaps.index(cells, Cells.getRowFunction()));
}

From source file:org.opentestsystem.authoring.testauth.publish.BasePublisherHelper.java

protected ItemPool setupItemPoolData(final Assessment assessment, final List<Item> itemList,
        final List<Segment> segmentList, final List<AffinityGroup> affinityGroupList, final String version) {
    final String assessmentId = assessment.getAssessmentId();
    final String assessmentUniqueId = buildIdentifier(assessment.getName(), assessment.getLabel(), version)
            .getUniqueId();/*from w  ww . j ava  2s  . c  o  m*/
    final ItemPool itemPool = new ItemPool();
    final List<ItemGroup> itemGroupList = this.itemGroupService.getItemGroupsByAssessment(assessmentId);
    final Map<String, ItemGroup> itemGroupMap = Maps.newHashMap();
    if (!CollectionUtils.isEmpty(itemGroupList)) {
        itemGroupMap.putAll(Maps.uniqueIndex(itemGroupList, ITEMGROUP_MAPKEY_TRANSFORMER));
    }
    itemPool.setTestItemList(nullsafeListTransform(itemList,
            ITEM_TESTITEM_TRANSFORMER.getInstance(itemGroupMap,
                    Maps.uniqueIndex(segmentList, SEGMENT_KEYID_TRANSFORMER),
                    Maps.uniqueIndex(affinityGroupList, AFFINITY_GROUP_KEYID_TRANSFORMER), assessmentUniqueId,
                    assessment.getClient())));
    // build up all the passages and use Set to pare down to unique instances
    // itemPool.setPassageList(Lists.newArrayList(Sets.newHashSet(nullsafeListTransform(itemList, ITEM_PASSAGE_TRANSFORMER))));
    // unique by uniqueId
    itemPool.setPassageList(
            buildUniquePassegesByUniqueId(nullsafeListTransform(itemList, ITEM_PASSAGE_TRANSFORMER)));

    final List<Enemy> enemyList = this.enemyService.getEnemiesByAssessmentId(assessmentId);
    if (!CollectionUtils.isEmpty(enemyList)) {
        final List<TestEnemyGroup> testEnemyGroupList = Lists.newArrayList();

        final Map<String, Collection<Enemy>> enemy1MultiMap = Multimaps
                .index(enemyList, ENEMY_TO_ENEMYID1_TRANSFORMER).asMap();
        for (final String enemy1Id : enemy1MultiMap.keySet()) {
            final List<Enemy> enemy1List = this.enemyService.getEnemiesByAssessmentIdAndObjectId1(assessmentId,
                    enemy1Id);
            testEnemyGroupList.add(new TestEnemyGroup(
                    buildTestEnemyGroupIdentifier(enemy1List.get(0).getObject1(), assessment.getItemBank()),
                    nullsafeListTransform(enemy1List,
                            ENEMY1_TRANSFORMER.getInstance(assessment.getItemBank()))));
        }
        final Map<String, Collection<Enemy>> enemy2MultiMap = Multimaps
                .index(enemyList, ENEMY_TO_ENEMYID2_TRANSFORMER).asMap();
        for (final String enemy2Id : enemy2MultiMap.keySet()) {
            final List<Enemy> enemy2List = this.enemyService.getEnemiesByAssessmentIdAndObjectId2(assessmentId,
                    enemy2Id);
            testEnemyGroupList.add(new TestEnemyGroup(
                    buildTestEnemyGroupIdentifier(enemy2List.get(0).getObject2(), assessment.getItemBank()),
                    nullsafeListTransform(enemy2List,
                            ENEMY2_TRANSFORMER.getInstance(assessment.getItemBank()))));
        }

        itemPool.setTestEnemyGroupList(testEnemyGroupList);
    }
    return itemPool;
}

From source file:com.facebook.swift.codec.metadata.AbstractThriftMetadataBuilder.java

protected final void normalizeThriftFields(ThriftCatalog catalog) {
    // assign all fields an id (if possible)
    Set<String> fieldsWithConflictingIds = inferThriftFieldIds();

    // group fields by id
    Multimap<Optional<Short>, FieldMetadata> fieldsById = Multimaps.index(fields, getThriftFieldId());
    for (Entry<Optional<Short>, Collection<FieldMetadata>> entry : fieldsById.asMap().entrySet()) {
        Collection<FieldMetadata> fields = entry.getValue();

        // fields must have an id
        if (!entry.getKey().isPresent()) {
            for (String fieldName : newTreeSet(transform(fields, getOrExtractThriftFieldName()))) {
                // only report errors for fields that don't have conflicting ids
                if (!fieldsWithConflictingIds.contains(fieldName)) {
                    metadataErrors.addError("Thrift class '%s' fields %s do not have an id", structName,
                            newTreeSet(transform(fields, getOrExtractThriftFieldName())));
                }//from   w  w  w.ja v a  2 s.c  om
            }
            continue;
        }

        short fieldId = entry.getKey().get();

        // ensure all fields for this ID have the same name
        String fieldName = extractFieldName(fieldId, fields);
        for (FieldMetadata field : fields) {
            field.setName(fieldName);
        }

        // ensure all fields for this ID have the same requiredness
        Requiredness requiredness = extractFieldRequiredness(fieldId, fieldName, fields);
        for (FieldMetadata field : fields) {
            field.setRequiredness(requiredness);
        }

        // We need to do the isLegacyId check in two places. We've already done this
        // process for fields which had multiple `@ThriftField` annotations when we
        // assigned them all the same ID. It doesn't hurt to do it again. On the other
        // hand, we need to do it now to catch the fields which only had a single
        // @ThriftAnnotation, because inferThriftFieldIds skipped them.
        boolean isLegacyId = extractFieldIsLegacyId(fieldId, fieldName, fields);
        for (FieldMetadata field : fields) {
            field.setIsLegacyId(isLegacyId);
        }

        // verify fields have a supported java type and all fields
        // for this ID have the same thrift type
        verifyFieldType(fieldId, fieldName, fields, catalog);
    }
}

From source file:com.facebook.swift.codec.metadata.ThriftStructMetadataBuilder.java

/**
 * Assigns all fields an id if possible.  Fields are grouped by name and for each group, if there
 * is a single id, all fields in the group are assigned this id.  If the group has multiple ids,
 * an error is reported./*from   ww  w.  ja  v  a 2  s  .  com*/
 */
private Set<String> inferThriftFieldIds() {
    Set<String> fieldsWithConflictingIds = new HashSet<>();

    // group fields by explicit name or by name extracted from field, method or property
    Multimap<String, FieldMetadata> fieldsByExplicitOrExtractedName = Multimaps.index(fields,
            getOrExtractThriftFieldName());
    inferThriftFieldIds(fieldsByExplicitOrExtractedName, fieldsWithConflictingIds);

    // group fields by name extracted from field, method or property
    // this allows thrift name to be set explicitly without having to duplicate the name on getters and setters
    // todo should this be the only way this works?
    Multimap<String, FieldMetadata> fieldsByExtractedName = Multimaps.index(fields, extractThriftFieldName());
    inferThriftFieldIds(fieldsByExtractedName, fieldsWithConflictingIds);

    return fieldsWithConflictingIds;
}