com.google.common.collect.Iterables#transform ( )源码实例Demo

下面列出了com.google.common.collect.Iterables#transform ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: pushfish-android   文件: SonarRunnerPlugin.java
private String convertValue(Object value) {
    if (value == null) {
        return null;
    }
    if (value instanceof Iterable<?>) {
        Iterable<String> flattened = Iterables.transform((Iterable<?>) value, new Function<Object, String>() {
            public String apply(Object input) {
                return convertValue(input);
            }
        });

        Iterable<String> filtered = Iterables.filter(flattened, Predicates.notNull());
        String joined = COMMA_JOINER.join(filtered);
        return joined.isEmpty() ? null : joined;
    } else {
        return value.toString();
    }
}
 
源代码2 项目: incubator-myriad   文件: TaskFactory.java
protected Iterable<Protos.Volume> getVolumes(Iterable<Map<String, String>> volume) {
  return Iterables.transform(volume, new Function<Map<String, String>, Protos.Volume>() {
    @Nullable
    @Override
    public Protos.Volume apply(Map<String, String> map) {
      Preconditions.checkArgument(map.containsKey(HOST_PATH_KEY) && map.containsKey(CONTAINER_PATH_KEY));
      Protos.Volume.Mode mode = Protos.Volume.Mode.RO;
      if (map.containsKey(RW_MODE) && map.get(RW_MODE).toLowerCase().equals("rw")) {
        mode = Protos.Volume.Mode.RW;
      }
      return Protos.Volume.newBuilder()
          .setContainerPath(map.get(CONTAINER_PATH_KEY))
          .setHostPath(map.get(HOST_PATH_KEY))
          .setMode(mode)
          .build();
    }
  });
}
 
源代码3 项目: xian   文件: TestingCluster.java
/**
 * Returns the set of servers in the ensemble
 *
 * @return set of servers
 */
public Collection<InstanceSpec> getInstances()
{
    Iterable<InstanceSpec> transformed = Iterables.transform
    (
        servers,
        new Function<TestingZooKeeperServer, InstanceSpec>()
        {
            @Override
            public InstanceSpec apply(TestingZooKeeperServer server)
            {
                return server.getInstanceSpec();
            }
        }
    );
    return Lists.newArrayList(transformed);
}
 
源代码4 项目: druid-api   文件: DimensionsSpec.java
@Deprecated @JsonIgnore
public List<SpatialDimensionSchema> getSpatialDimensions()
{
  Iterable<NewSpatialDimensionSchema> filteredList = Iterables.filter(
      dimensions, NewSpatialDimensionSchema.class
  );

  Iterable<SpatialDimensionSchema> transformedList = Iterables.transform(
      filteredList,
      new Function<NewSpatialDimensionSchema, SpatialDimensionSchema>()
      {
        @Nullable
        @Override
        public SpatialDimensionSchema apply(NewSpatialDimensionSchema input)
        {
          return new SpatialDimensionSchema(input.getName(), input.getDims());
        }
      }
  );

  return Lists.newArrayList(transformedList);
}
 
源代码5 项目: estatio   文件: PostalAddressRepository.java
@Programmatic
public PostalAddress findByAddress(
        final CommunicationChannelOwner owner,
        final String address1,
        final String address2,
        final String address3,
        final String postalCode,
        final String city,
        final Country country) {

    final List<CommunicationChannelOwnerLink> links =
            communicationChannelOwnerLinkRepository.findByOwnerAndCommunicationChannelType(owner, CommunicationChannelType.POSTAL_ADDRESS);
    final Iterable<PostalAddress> postalAddresses =
            Iterables.transform(
                    links,
                    CommunicationChannelOwnerLink.Functions.communicationChannel(PostalAddress.class));
    final Optional<PostalAddress> postalAddressIfFound =
            Iterables.tryFind(postalAddresses, PostalAddress.Predicates.equalTo(address1, address2, address3, postalCode, city, country));
    return postalAddressIfFound.orNull();
}
 
源代码6 项目: statecharts   文件: SCTUnitTestModels.java
public static Iterable<Object[]> parameterizedTestData() throws Exception {
	SCTUnitTestModels models = new SCTUnitTestModels();
	List<Statechart> all = models.loadAllStatecharts();
	return Iterables.transform(all, new Function<Statechart, Object[]>() {
		@Override
		public Object[] apply(Statechart input) {
			return new Object[]{input};
		}
	});
}
 
源代码7 项目: datawave   文件: Intersection.java
static Iterable<IndexInfo> convert(Iterable<? extends PeekingIterator<Tuple2<String,IndexInfo>>> i) {
    final Function<PeekingIterator<Tuple2<String,IndexInfo>>,IndexInfo> f = itr -> {
        if (log.isTraceEnabled())
            log.trace("ah" + itr.peek().first() + " " + itr.peek().second());
        return itr.peek().second();
    };
    return Iterables.transform(i, f);
}
 
源代码8 项目: brooklyn-server   文件: MultiLocationRebindTest.java
@SuppressWarnings("unchecked")
@Test
public void testRebindsMultiLocation() throws Exception {
    mac1a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
            .displayName("mac1a")
            .configure("address", Networking.getInetAddressWithFixedName("1.1.1.1")));
    mac2a = origManagementContext.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
            .displayName("mac2a")
            .configure("address", Networking.getInetAddressWithFixedName("1.1.1.3")));
    loc1 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
            .displayName("loc1")
            .configure("machines", MutableSet.of(mac1a)));
    loc2 = origManagementContext.getLocationManager().createLocation(LocationSpec.create(FixedListMachineProvisioningLocation.class)
            .displayName("loc2")
            .configure("machines", MutableSet.of(mac2a)));
    multiLoc = origManagementContext.getLocationManager().createLocation(LocationSpec.create(MultiLocation.class)
                    .displayName("multiLoc")
                    .configure("subLocations", ImmutableList.of(loc1, loc2)));
    
    newApp = rebind();
    newManagementContext = newApp.getManagementContext();
    
    MultiLocation<?> newMultiLoc = (MultiLocation<?>) Iterables.find(newManagementContext.getLocationManager().getLocations(), Predicates.instanceOf(MultiLocation.class));
    AvailabilityZoneExtension azExtension = newMultiLoc.getExtension(AvailabilityZoneExtension.class);
    List<Location> newSublLocs = azExtension.getAllSubLocations();
    Iterable<String> newSubLocNames = Iterables.transform(newSublLocs, new Function<Location, String>() {
        @Override public String apply(Location input) {
            return (input == null) ? null : input.getDisplayName();
        }});
    Asserts.assertEqualsIgnoringOrder(newSubLocNames, ImmutableList.of("loc1", "loc2"));
}
 
源代码9 项目: dsl-devkit   文件: DelegatingScope.java
/**
 * Evaluate the delegate scopes.
 *
 * @return The delegate scopes.
 */
protected Iterable<IScope> getDelegates() {
  if (delegates == null) {
    delegates = Iterables.transform(contexts.get(), o -> {
      try {
        return eReference != null ? scopeProvider.getScope(o, eReference, scopeName, originalResource)
            : scopeProvider.getScope(o, eClass, scopeName, originalResource);
      } catch (StackOverflowError e) {
        stackOverflowScopeId = DelegatingScope.this.getId();
        return STACK_OVERFLOW_SCOPE;
      }
    });
  }
  return delegates;
}
 
源代码10 项目: yql-plus   文件: SourceUnitGenerator.java
@Override
public void complete(ObjectBuilder.MethodBuilder adapterMethod, ScopedBuilder body) {
    // we need to surface optional/required arguments and a suitable struct type to populate the planner
    // so let's make a YQL schema for our argument map
    this.insertType = argumentMap.build();
    // derive a struct type from it
    // that is the type our adapter method takes as an argument
    // it then needs to explode that into the arguments to the method
    TypeWidget insertRecord = AnyTypeWidget.getInstance();
    BytecodeExpression record = adapterMethod.addArgument("$record", insertRecord);
    // scatter the record in key into all the key values
    // TODO: check data types before blind coercion attempts!
    for (Map.Entry<String, AssignableValue> keyEntry : dataValues.entrySet()) {
        String propertyName = keyEntry.getKey();
        BytecodeExpression defaultValue = defaultValues.get(propertyName);
        AssignableValue setValue = keyEntry.getValue();
        if(defaultValue == null) {
            defaultValue = new MissingRequiredFieldExpr(clazz.getName(), this.method.getName(), propertyName, setValue.getType());
        }
        body.set(Location.NONE, setValue, body.cast(setValue.getType(), body.coalesce(Location.NONE, body.propertyValue(Location.NONE, record, propertyName), defaultValue)));
    }
    // verify we didn't get any unrecognized fields
    if(insertType.isClosed()) {
        PropertyAdapter adapter = insertRecord.getPropertyAdapter();
        TreeSet<String> fieldNames = Sets.newTreeSet(String.CASE_INSENSITIVE_ORDER);
        for(String name : Iterables.transform(insertType.getFields(), new Function<YQLNamePair, String>() {
                    @Nullable
                    @Override
                    public String apply(YQLNamePair input) {
                        return input.getName();
                    }
                })) {
            fieldNames.add(name);
        }
        body.exec(adapter.mergeIntoFieldWriter(record, body.constant(body.adapt(FieldWriter.class, false), new VerifyNoExtraFieldsFieldWriter(fieldNames, clazz.getName(), this.method.getName()))));
    }

}
 
源代码11 项目: n4js   文件: FilterWithErrorMarkerScope.java
/**
 * Decorates all descriptions which are filtered with error markers. Since
 * {@link #wrapFilteredDescription(IEObjectDescription)} may return null, null values are filtered out.
 *
 * @param originalDescriptions
 *            the original unfiltered descriptions.
 */
protected Iterable<IEObjectDescription> doDecorateWithErrorIfFiltered(
		Iterable<IEObjectDescription> originalDescriptions, Predicate<IEObjectDescription> predicate) {
	Iterable<IEObjectDescription> filteredResult = Iterables.transform(originalDescriptions,
			it -> {
				if (it == null || predicate.test(it)) {
					return it;
				} else {
					return wrapFilteredDescription(it);
				}
			});
	return Iterables.filter(filteredResult, it -> it != null);
}
 
源代码12 项目: gama   文件: GamlExpressionCompiler.java
@Override
public IExpression caseArray(final Array object) {
	final List<? extends Expression> list = EGaml.getInstance().getExprsOf(object.getExprs());
	// Awkward expression, but necessary to fix Issue #2612
	final boolean allPairs = !list.isEmpty() && Iterables.all(list,
			each -> each instanceof ArgumentPair || "::".equals(EGaml.getInstance().getKeyOf(each)));
	final Iterable<IExpression> result = Iterables.transform(list, input -> compile(input));
	return allPairs ? getFactory().createMap(result) : getFactory().createList(result);
}
 
源代码13 项目: morf   文件: MySqlDialect.java
/**
 * @see org.alfasoftware.morf.jdbc.SqlDialect#getSqlFrom(org.alfasoftware.morf.sql.MergeStatement)
 */
@Override
protected String getSqlFrom(final MergeStatement statement) {

  if (StringUtils.isBlank(statement.getTable().getName())) {
    throw new IllegalArgumentException("Cannot create SQL for a blank table");
  }

  checkSelectStatementHasNoHints(statement.getSelectStatement(), "MERGE may not be used with SELECT statement hints");

  final boolean hasNonKeyFields = getNonKeyFieldsFromMergeStatement(statement).iterator().hasNext();

  final String destinationTableName = statement.getTable().getName();

  // Add the preamble
  StringBuilder sqlBuilder = new StringBuilder("INSERT ");
  if (!hasNonKeyFields) {
    sqlBuilder.append("IGNORE ");
  }
  sqlBuilder.append("INTO ");
  sqlBuilder.append(schemaNamePrefix(statement.getTable()));
  sqlBuilder.append(destinationTableName);
  sqlBuilder.append("(");
  Iterable<String> intoFields = Iterables.transform(statement.getSelectStatement().getFields(), AliasedField::getImpliedName);
  sqlBuilder.append(Joiner.on(", ").join(intoFields));
  sqlBuilder.append(") ");

  // Add select statement
  sqlBuilder.append(getSqlFrom(statement.getSelectStatement()));

  // Add the update expressions
  if (hasNonKeyFields) {
    sqlBuilder.append(" ON DUPLICATE KEY UPDATE ");
    Iterable<AliasedField> updateExpressions = getMergeStatementUpdateExpressions(statement);
    String updateExpressionsSql = getMergeStatementAssignmentsSql(updateExpressions);
    sqlBuilder.append(updateExpressionsSql);
  }
  return sqlBuilder.toString();
}
 
源代码14 项目: powsybl-core   文件: BusAdapter.java
@Override
public Iterable<Load> getLoads() {
    return Iterables.transform(getDelegate().getLoads(),
                               getIndex()::getLoad);
}
 
源代码15 项目: bazel   文件: Interspersing.java
/**
 * Prepends {@code what} to each string in {@code sequence}, returning a lazy sequence of the 
 * same length.
 */
public static Iterable<String>
    prependEach(final String what, Iterable<String> sequence) {
  Preconditions.checkNotNull(what);
  return Iterables.transform(sequence, input -> what + input);
}
 
源代码16 项目: bazel   文件: TargetParsingCompleteEvent.java
public Iterable<Label> getFilteredLabels() {
  return Iterables.transform(filteredTargets, ThinTarget::getLabel);
}
 
源代码17 项目: powsybl-core   文件: SubstationAdapter.java
@Override
public Iterable<TwoWindingsTransformer> getTwoWindingsTransformers() {
    return Iterables.transform(getDelegate().getTwoWindingsTransformers(),
                               getIndex()::getTwoWindingsTransformer);
}
 
源代码18 项目: fluo   文件: StochasticBankIT.java
private static void printDiffs(Environment env, TestTransaction lastTx, TestTransaction tx)
    throws Exception {
  Map<String, String> bals1 = toMap(lastTx);
  Map<String, String> bals2 = toMap(tx);

  if (!bals1.keySet().equals(bals2.keySet())) {
    log.debug("KS NOT EQ");
  }

  int sum1 = 0;
  int sum2 = 0;

  for (Entry<String, String> entry : bals1.entrySet()) {
    String val2 = bals2.get(entry.getKey());

    if (!entry.getValue().equals(val2)) {
      int v1 = Integer.parseInt(entry.getValue());
      int v2 = Integer.parseInt(val2);
      sum1 += v1;
      sum2 += v2;

      log.debug(entry.getKey() + " " + entry.getValue() + " " + val2 + " " + (v2 - v1));
    }
  }

  log.debug("start times : " + lastTx.getStartTs() + " " + tx.getStartTs());
  log.debug("sum1 : %,d  sum2 : %,d  diff : %,d\n", sum1, sum2, sum2 - sum1);

  File tmpFile = File.createTempFile("sb_dump", ".txt");
  Writer fw = new BufferedWriter(new FileWriter(tmpFile));

  Scanner scanner =
      env.getAccumuloClient().createScanner(env.getTable(), env.getAuthorizations());

  for (String cell : Iterables.transform(scanner, FluoFormatter::toString)) {
    fw.append(cell);
    fw.append("\n");
  }

  fw.close();

  log.debug("Dumped table : " + tmpFile);
}
 
源代码19 项目: bazel   文件: LinkerInputs.java
/**
 * Creates input libraries for which we do not know what objects files it consists of.
 */
public static Iterable<LibraryToLink> opaqueLibrariesToLink(
    final ArtifactCategory category, Iterable<Artifact> input) {
  return Iterables.transform(input, artifact -> precompiledLibraryToLink(artifact, category));
}
 
源代码20 项目: attic-aurora   文件: ResourceCounter.java
private Iterable<ITaskConfig> getTasks(Query.Builder query) throws StorageException {
  return Iterables.transform(
      Storage.Util.fetchTasks(storage, query),
      Tasks::getConfig);
}