Java Code Examples for java.util.function.Function#apply()

The following examples show how to use java.util.function.Function#apply() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
<T, S extends BaseStream<T, S>> void testStreamTooLarge(Function<LongStream, S> s,
                                                        Function<S, ?> terminal) {
    // Set up conditions for a large input > maximum array size
    Supplier<LongStream> input = () -> LongStream.range(0, 1L + Integer.MAX_VALUE);

    // Transformation functions
    List<Function<LongStream, LongStream>> transforms = Arrays.asList(
            ls -> ls,
            ls -> ls.parallel(),
            // Clear the SIZED flag
            ls -> ls.limit(Long.MAX_VALUE),
            ls -> ls.limit(Long.MAX_VALUE).parallel());

    for (Function<LongStream, LongStream> transform : transforms) {
        RuntimeException caught = null;
        try {
            terminal.apply(s.apply(transform.apply(input.get())));
        } catch (RuntimeException e) {
            caught = e;
        }
        assertNotNull(caught, "Expected an instance of exception IllegalArgumentException but no exception thrown");
        assertTrue(caught instanceof IllegalArgumentException,
                   String.format("Expected an instance of exception IllegalArgumentException but got %s", caught));
    }
}
 
Example 2
Source Project: vespa   File: SystemFlagsDeployResult.java    License: Apache License 2.0 6 votes vote down vote up
private static <VALUE, VALUE_WITHOUT_TARGET> List<VALUE> merge(
        List<SystemFlagsDeployResult> results,
        Function<SystemFlagsDeployResult, List<VALUE>> valuesGetter,
        Function<VALUE, Set<FlagsTarget>> targetsGetter,
        Function<VALUE, VALUE_WITHOUT_TARGET> transformer,
        BiFunction<VALUE_WITHOUT_TARGET, Set<FlagsTarget>, VALUE> reverseTransformer) {
    Map<VALUE_WITHOUT_TARGET, Set<FlagsTarget>> targetsForValue = new HashMap<>();
    for (SystemFlagsDeployResult result : results) {
        for (VALUE value : valuesGetter.apply(result)) {
            VALUE_WITHOUT_TARGET valueWithoutTarget = transformer.apply(value);
            targetsForValue.computeIfAbsent(valueWithoutTarget, k -> new HashSet<>())
                    .addAll(targetsGetter.apply(value));
        }
    }
    List<VALUE> mergedValues = new ArrayList<>();
    targetsForValue.forEach(
            (value, targets) -> mergedValues.add(reverseTransformer.apply(value, targets)));
    return mergedValues;
}
 
Example 3
Source Project: iceberg   File: StructInternalRow.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> GenericArrayData fillArray(Collection<?> values, Function<Object[], BiConsumer<Integer, T>> makeSetter) {
  Object[] array = new Object[values.size()];
  BiConsumer<Integer, T> setter = makeSetter.apply(array);

  int index = 0;
  for (Object value : values) {
    if (value == null) {
      array[index] = null;
    } else {
      setter.accept(index, (T) value);
    }

    index += 1;
  }

  return new GenericArrayData(array);
}
 
Example 4
@Test(dataProvider = "doubleViewProvider")
public void testDoubleGet(String desc, IntFunction<ByteBuffer> fbb,
                          Function<ByteBuffer, DoubleBuffer> fbi) {
    ByteBuffer bb = allocate(fbb);
    DoubleBuffer vb = fbi.apply(bb);
    int o = bb.position();

    for (int i = 0; i < vb.limit(); i++) {
        double fromBytes = getDoubleFromBytes(bb, o + i * 8);
        double fromMethodView = bb.getDouble(o + i * 8);
        assertValues(i, fromBytes, fromMethodView, bb);

        double fromBufferView = vb.get(i);
        assertValues(i, fromMethodView, fromBufferView, bb, vb);
    }

    for (int i = 0; i < vb.limit(); i++) {
        double v = getDoubleFromBytes(bb, o + i * 8);
        double a = bb.getDouble();
        assertValues(i, v, a, bb);

        double b = vb.get();
        assertValues(i, a, b, bb, vb);
    }

}
 
Example 5
/**
 * Returns a function that translate an source line string value array into
 * into a interval.
 *
 * @param contigColumnNumber    the number of the input column that contains the
 *                              contig name. {@code -1} if missing.
 * @param startColumnNumber     the number of the input column that contains the
 *                              start position. {@code -1} if missing.
 * @param endColumnNumber       the number of the input column that contains the
 *                              end position. {@code -1} if missing.
 * @param errorExceptionFactory instantiates the exception to thrown in case
 *                              of a formatting error. cannot be {@code null}.
 * @return not a {@code null} if there is enough information to find out the
 * sample intervals, {@code null} if it is insufficient.
 */
private static Function<DataLine, SimpleInterval> composeIntervalBuilder(
        final int contigColumnNumber,final int startColumnNumber, final int endColumnNumber,
        final Function<String, RuntimeException> errorExceptionFactory) {
    if (contigColumnNumber == -1 || startColumnNumber == -1 || endColumnNumber == -1) {
        return null;
    }

    return (v) -> {
        final String contig = v.get(contigColumnNumber);
        final int start = v.getInt(startColumnNumber);
        final int end = v.getInt(endColumnNumber);
        if (start <= 0) {
            throw errorExceptionFactory.apply(String.format("start position must be greater than 0: %d", start));
        } else if (start > end) {
            throw errorExceptionFactory.apply(String.format("end position '%d' must equal or greater than the start position '%d'", end, start));
        } else {
            return new SimpleInterval(contig, start, end);
        }
    };
}
 
Example 6
Source Project: Voovan   File: RocksMap.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 开启式事务模式
 *      同一个线程共线给一个事务
 *      使用内置公共事务通过 savepoint 来失败回滚, 但统一提交, 性能会好很多, 但是由于很多层嵌套的 savepont 在高并发时使用这种方式时回导致提交会慢很多
 * @param expire         提交时锁超时时间
 * @param deadlockDetect 死锁检测是否打开
 * @param withSnapShot   是否启用快照事务
 * @param transFunction 事务执行器, 返回 Null 则事务回滚, 其他则事务提交
 * @param <T>  范型
 * @return 非 null: 事务成功, null: 事务失败
 */
public <T> T withTransaction(long expire, boolean deadlockDetect, boolean withSnapShot, Function<RocksMap<K, V>, T> transFunction) {
    beginTransaction(expire, deadlockDetect, withSnapShot);

    try {
        T object = transFunction.apply(this);
        if (object == null) {
            rollback();
        } else {
            commit();
        }
        return object;
    } catch (Exception e) {
        rollback();
        throw e;
    }
}
 
Example 7
/**
 * Iterates through the statically registered {@link #sectionProviderFactoryFuncs factory funcs},
 * trying each factory method until one returns a {@link DWARFSectionProvider} 
 * that can successfully retrieve the {@link DWARFSectionNames#MINIMAL_DWARF_SECTIONS minimal} 
 * sections we need to do a DWARF import.
 * <p>
 * The resulting {@link DWARFSectionProvider} is {@link Closeable} and it is the caller's
 * responsibility to ensure that the object is closed when done. 
 * 
 * @param program
 * @return {@link DWARFSectionProvider} that should be closed by the caller or NULL if no
 * section provider types match the specified program.
 */
public static DWARFSectionProvider createSectionProviderFor(Program program) {
	for (Function<Program, DWARFSectionProvider> factoryFunc : sectionProviderFactoryFuncs) {
		DWARFSectionProvider sp = factoryFunc.apply(program);
		if (sp != null) {
			try {
				if (sp.hasSection(DWARFSectionNames.MINIMAL_DWARF_SECTIONS)) {
					return sp;
				}
			}
			catch (Exception e) {
				Msg.warn(DWARFSectionProviderFactory.class,
					"Problem detecting DWARFSectionProvider", e);
			}
			sp.close();
		}
	}
	return null;
}
 
Example 8
public <E extends JobDescriptorExt> JobsScenarioBuilder inJob(int idx, Function<JobScenarioBuilder<E>, JobScenarioBuilder<E>> jobScenario) {
    JobScenarioBuilder<E> jobScenarioBuilder = getJobScenario(idx);
    if (jobScenarioBuilder == null) {
        throw new IllegalArgumentException(String.format("No job with index %s registered", idx));
    }
    jobScenario.apply(jobScenarioBuilder);
    return this;
}
 
Example 9
Source Project: tinkerpop   File: GryoReader.java    License: Apache License 2.0 5 votes vote down vote up
private Vertex readVertexInternal(final Function<Attachable<Vertex>, Vertex> vertexMaker,
                                  final Function<Attachable<Edge>, Edge> edgeMaker,
                                  final Direction d,
                                  final Input input) throws IOException {
    readHeader(input);
    final StarGraph starGraph = kryo.readObject(input, StarGraph.class);

    // read the terminator
    kryo.readClassAndObject(input);

    final Vertex v = vertexMaker.apply(starGraph.getStarVertex());
    if (edgeMaker != null)
        starGraph.getStarVertex().edges(d).forEachRemaining(e -> edgeMaker.apply((Attachable<Edge>) e));
    return v;
}
 
Example 10
/**
   * Setup Stream topology
   * Add KStream based on @StreamListener annotation
   * Add to(topic) based @SendTo annotation
   */
  @Before
  public void setup() {
      final StreamsBuilder builder = new StreamsBuilder();
      KStream<Bytes, String> input = builder.stream(INPUT_TOPIC, Consumed.with(nullSerde, stringSerde));
      KafkaStreamsWordCountApplication.WordCountProcessorApplication app = new KafkaStreamsWordCountApplication.WordCountProcessorApplication();
      final Function<KStream<Bytes, String>, KStream<Bytes, KafkaStreamsWordCountApplication.WordCount>> process = app.process();

final KStream<Bytes, KafkaStreamsWordCountApplication.WordCount> output = process.apply(input);

output.to(OUTPUT_TOPIC, Produced.with(nullSerde, countSerde));

      testDriver = new TopologyTestDriver(builder.build(), getStreamsConfiguration());
  }
 
Example 11
@Override
public String methodWithDataObjectReturn(Function<String, TestDataObject> func) {
  TestDataObject val = func.apply("whatever");
  assertEquals("wasabi", val.getFoo());
  assertEquals(6, val.getBar());
  assertEquals(0.01D, val.getWibble(), 0.001D);
  return "ok";
}
 
Example 12
Source Project: buck   File: CxxSourceRuleFactory.java    License: Apache License 2.0 5 votes vote down vote up
/** Quick and dirty memoized function. */
private static <K, V> Function<K, V> memoize(Function<K, V> mappingFunction) {
  HashMap<K, V> cache = new HashMap<>();
  return k -> {
    V value = cache.get(k);
    if (value != null) {
      return value;
    }
    value = mappingFunction.apply(k);
    cache.put(k, value);
    return value;
  };
}
 
Example 13
@Override
protected CommandResponse doCreateResponse(
        final Function<ResponseFactory, CommandResponse<?>> createResponseFunction) {
    return createResponseFunction.apply(new ResponseFactoryImpl());
}
 
Example 14
private static String testFirstClassFunction1(int n, Function<Integer, String> f) {
  return "The result is " + f.apply(n) + ".";
}
 
Example 15
Source Project: cyclops   File: Nested.java    License: Apache License 2.0 4 votes vote down vote up
public <R> R foldRight(Monoid<T> monoid, Function<? super Higher<W1,T>,? extends R> narrowK){
    return narrowK.apply(foldRight(monoid));
}
 
Example 16
/**
 * Perform additional transformation on the parsed object.
 */
default <U> ResponseReader<U> andThen(Function<T, U> f) {
  return bytes -> f.apply(read(bytes));
}
 
Example 17
Source Project: cyclops   File: Comonad.java    License: Apache License 2.0 4 votes vote down vote up
default <T, R> Function<Higher<CRE, T>, R> liftComonad(Function<? super T,? extends R> fn) {
    return higher -> fn.apply(extract(higher));
}
 
Example 18
/**
 * {@inheritDoc}
 *
 * @implSpec
 * The default implementation is equivalent to the following steps for this
 * {@code map}, then returning the current value or {@code null} if now
 * absent:
 *
 * <pre> {@code
 * if (map.get(key) == null) {
 *     V newValue = mappingFunction.apply(key);
 *     if (newValue != null)
 *         return map.putIfAbsent(key, newValue);
 * }
 * }</pre>
 *
 * The default implementation may retry these steps when multiple
 * threads attempt updates including potentially calling the mapping
 * function multiple times.
 *
 * <p>This implementation assumes that the ConcurrentMap cannot contain null
 * values and {@code get()} returning null unambiguously means the key is
 * absent. Implementations which support null values <strong>must</strong>
 * override this default implementation.
 *
 * @throws UnsupportedOperationException {@inheritDoc}
 * @throws ClassCastException {@inheritDoc}
 * @throws NullPointerException {@inheritDoc}
 * @since 1.8
 */
@Override
default V computeIfAbsent(K key,
        Function<? super K, ? extends V> mappingFunction) {
    Objects.requireNonNull(mappingFunction);
    V v, newValue;
    return ((v = get(key)) == null &&
            (newValue = mappingFunction.apply(key)) != null &&
            (v = putIfAbsent(key, newValue)) == null) ? newValue : v;
}
 
Example 19
Source Project: atomix   File: DefaultProxySession.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Invokes a function on the underlying proxy.
 *
 * @param operation the operation to perform on the proxy
 * @param <T>       the operation return type
 * @return the future result
 */
<T> CompletableFuture<T> apply(Function<S, T> operation) {
  operation.apply(proxy);
  return handler.getResultFuture();
}
 
Example 20
Source Project: reactor-core   File: Tuple6.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Map the 1st part (T1) of this {@link Tuple6} into a different value and type,
 * keeping the other parts.
 *
 * @param mapper the mapping {@link Function} for the T1 part
 * @param <R> the new type for the T1 part
 * @return a new {@link Tuple6} with a different T1 value
 */
public <R> Tuple6<R, T2, T3, T4, T5, T6> mapT1(Function<T1, R> mapper) {
	return new Tuple6<>(mapper.apply(t1), t2, t3, t4, t5, t6);
}