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

The following examples show how to use java.util.function.Function#apply() . 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
Source File: DWARFSectionProviderFactory.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * 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 2
Source File: SortedOpTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
<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 3
Source File: RocksMap.java    From Voovan with 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 4
Source File: SystemFlagsDeployResult.java    From vespa with 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 5
Source File: ReadCountsReader.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 File: StructInternalRow.java    From iceberg with 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 7
Source File: ByteBufferViews.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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 8
Source File: JobsScenarioBuilder.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
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 File: CxxSourceRuleFactory.java    From buck with 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 10
Source File: FunctionParamTCKImpl.java    From vertx-codegen with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: WordCountProcessorApplicationTests.java    From spring-cloud-stream-samples with Apache License 2.0 5 votes vote down vote up
/**
   * 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 12
Source File: GryoReader.java    From tinkerpop with 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 13
Source File: Nested.java    From cyclops with 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 14
Source File: Pubsub.java    From async-google-pubsub-client with Apache License 2.0 4 votes vote down vote up
/**
 * Perform additional transformation on the parsed object.
 */
default <U> ResponseReader<U> andThen(Function<T, U> f) {
  return bytes -> f.apply(read(bytes));
}
 
Example 15
Source File: MethodReferenceExamples.java    From modern-java-untold with Apache License 2.0 4 votes vote down vote up
private static String testFirstClassFunction1(int n, Function<Integer, String> f) {
  return "The result is " + f.apply(n) + ".";
}
 
Example 16
Source File: ModifyFeaturePropertyLiveCommandAnswerBuilderImpl.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected CommandResponse doCreateResponse(
        final Function<ResponseFactory, CommandResponse<?>> createResponseFunction) {
    return createResponseFunction.apply(new ResponseFactoryImpl());
}
 
Example 17
Source File: Comonad.java    From cyclops with 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
Source File: ConcurrentMap.java    From jdk8u-dev-jdk with GNU General Public License v2.0 3 votes vote down vote up
/**
 * {@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 File: DefaultProxySession.java    From atomix with 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 File: Tuple6.java    From reactor-core with 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);
}