public T match(String s) { Matcher m = pattern.matcher(s); if (m.find()) { return parser.apply(m.group(m.groupCount())); } return parser.apply(null); }
@Test public void test0() { Function<Integer, Integer> f = ((Integer) 0)::compareTo; Function<Integer, Integer> f1 = f.compose(f); // f1 does what?! }
@Test public void converts() throws Exception { Function<Double, Double> converterFunction = new Converter_1_2().apply(CONVERSION_RATE); assertEquals(4.5, converterFunction.apply(3.0), 0.0001); assertEquals(6.0, converterFunction.apply(4.0), 0.0001); assertEquals(7.5, converterFunction.apply(5.0), 0.0001); }
public List<T> collect() { List<T> list = new ArrayList<>(); for (Pair<String, String> p : map.keySet()) { String folder = p.first; String pattern = p.second; Function<String, ? extends T> func = map.get(p); DirectoryStream<Path> dirStream; try { dirStream = Files.newDirectoryStream(Paths.get(folder), pattern); logger.info(String.format("Load files from folder %s with pattern %s.", folder, pattern)); // sort the files List<String> files = new ArrayList<>(); dirStream.forEach(s -> files.add(s.toString())); Collections.sort(files); for (String s : files) { logger.info(String.format("Loading file %s.", s)); list.add(func.apply(s)); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(String.format("Could not load files from patern: %s", pattern)); } } return list; }
public void set(T result) { try { final Object use = result; if (pipeline == null || pipeline.functions.length == 0) { this.result.lazySet(use); done(); return; } Function op = pipeline.functions[0]; if (this.pipeline.executors[0] != null) { this.pipeline.executors[0].execute( () -> { set(() -> (T) op.apply(use), 1); }); } else { set(() -> (T) op.apply(use), 1); } } catch (Throwable t) { completeExceptionally(t); } }
private void set(Supplier<T> result, int index) { try { Object current = result.get(); final Object use = current; if (index < pipeline.functions.length) { Function op = pipeline.functions[index]; this.pipeline.executors[index].execute( () -> { set(() -> (T) op.apply(use), index + 1); }); return; } this.result.lazySet(current); done(); } catch (Throwable t) { if (t instanceof CompletedException) { if (this.doFinally != null) doFinally.accept(this); } completeExceptionally(t); } }
public static void main(String[] args) { // Write custom functional interfaces that can be implemented via lambda expressions. ReverseType newText = (testText) -> { String tempStr = ""; for (String part : testText.split(" ")) { tempStr = new StringBuilder(part).reverse().toString(); } return tempStr; }; System.out.println(newText.reverse("HELLO")); // Use a functional interface that is contained within the java.util.function package to // implement a lambda expression Function<String, String> newText2 = (testText) -> { String tempStr = ""; for (String part : testText.split(" ")) { tempStr = new StringBuilder(part).reverse().toString(); } return tempStr; }; System.out.println(newText2.apply("WORLD")); }
@Before public void setUp() { consumersForMergeParams.put(OrderEventType.MERGE_OK, eventConsumerMock); consumersForMergeParams.put(OrderEventType.MERGE_REJECTED, eventConsumerMock); when(actionConsumerMock.apply(orderForTest)).thenReturn(actionMock); when(mergePositionParamsMock.instrument()).thenReturn(instrumentEURUSD); when(mergePositionParamsMock.mergeOrderLabel()).thenReturn(mergeOrderLabel); when(mergePositionParamsMock.consumerForEvent()).thenReturn(consumersForMergeParams); when(closePositionComposeParamsMock.composeData()).thenReturn(composeData); closeParams = CloseParams.withOrder(orderForTest) .doOnStart(actionMock) .doOnComplete(actionMock) .doOnError(errorConsumerMock) .retryOnReject(retryParams) .doOnClose(eventConsumerMock) .doOnPartialClose(eventConsumerMock) .doOnReject(eventConsumerMock) .build(); when(closeParamsFactoryMock.apply(orderForTest)).thenReturn(closeParams); closePositionParams = ClosePositionParams.newBuilder(mergePositionParamsMock, closeParamsFactoryMock) .withCloseExecutionMode(CloseExecutionMode.CloseFilled) .withClosePositonParams(closePositionComposeParamsMock) .build(); }
public static <T, U> Function<T, U> ternaryOperator( Predicate<? super T> condition, Function<? super T, ? extends U> ifTrue, Function<? super T, ? extends U> ifFalse) { return (x -> condition.test(x) ? ifTrue.apply(x) : ifFalse.apply(x)); }
public static void main(String... args) { Function<String, String> addHeader = Letter::addHeader; Function<String, String> transformationPipeline = addHeader.andThen(Letter::checkSpelling).andThen(Letter::addFooter); System.out.println(transformationPipeline.apply("C++ stay away from me!")); }
protected JsonNode loadConfiguration(Map<String, String> properties, Map<String, String> vars) { // hopefully sharing the mapper between parsers is safe... Does it // change the state during parse? ObjectMapper textToJsonMapper = jacksonService.newObjectMapper(); Map<ParserType, Function<InputStream, Optional<JsonNode>>> parsers = new EnumMap<>(ParserType.class); parsers.put(ParserType.YAML, new JsonNodeYamlParser(textToJsonMapper)); parsers.put(ParserType.JSON, new JsonNodeJsonParser(textToJsonMapper)); Function<URL, Optional<JsonNode>> parser = new MultiFormatJsonNodeParser(parsers, bootLogger); BinaryOperator<JsonNode> singleConfigMerger = new InPlaceLeftHandMerger(bootLogger); Function<JsonNode, JsonNode> overrider = new InPlaceMapOverrider(properties, true, '.'); if (!vars.isEmpty()) { overrider = overrider.andThen(new InPlaceMapOverrider(vars, false, '_')); } return JsonNodeConfigurationBuilder.builder() .parser(parser) .merger(singleConfigMerger) .resources(configurationSource) .overrider(overrider) .build(); }
public GExpansion rewrite(Function<GExpansion, GExpansion> f) { switch (kind) { case LookAhead: if (semanticLookahead != null || amount != -1) { return f.apply(this); } case Choice: case Sequence: case ZeroOrOne: case ZeroOrMore: case OneOrMore: List<GExpansion> rewroteChildren = children.stream().map(e -> e.rewrite(f)).collect(Collectors.toList()); return f.apply( new GExpansion( kind, rewroteChildren, name, symbol, hints, arguments, action, amount, semanticLookahead, negativeLookahead)); case NonTerminal: case Terminal: case Action: return f.apply(this); default: } return null; }
@Override public void forEachRemaining(Consumer<? super R> action) { while (left != null) { accept(handleLeft(), action); } if (cur == none()) { if (!source.tryAdvance(this)) { accept(pushRight(none(), none()), action); return; } } acc = mapper.apply(cur); source.forEachRemaining( next -> { if (!this.mergeable.test(cur, next)) { action.accept(acc); acc = mapper.apply(next); } else { acc = accumulator.apply(acc, next); } cur = next; }); if (accept(pushRight(acc, cur), action)) { if (right != null) { action.accept(right.acc); right = null; } } }
public static void main(String[] args) { Function<String, Integer> f1 = String::length; Function<String, Integer> f2 = x -> x.length(); System.out.println(f1.apply("cluck")); // 5 System.out.println(f2.apply("cluckssss")); // }
/** * Calculates the minimum of this elements within the co-domain of a specific function. * * @param f A function that maps this elements to comparable elements * @param <U> The type where elements are compared * @return The element of type T which is the minimum within U */ default <U extends Comparable<? super U>> Option<T> minBy(Function<? super T, ? extends U> f) { Objects.requireNonNull(f, "f is null"); if (isEmpty()) { return None.instance(); } else { return minBy((t1, t2) -> f.apply(t1).compareTo(f.apply(t2))); } }
@Test public void test2() { Function<Integer, Integer> f = ((Function<Integer, Integer>) ((Integer) 0)::compareTo).compose(((Integer) 0)::compareTo); Assert.assertEquals(Integer.valueOf(0), f.apply(0)); Assert.assertEquals(Integer.valueOf(1), f.apply(100)); Assert.assertEquals(Integer.valueOf(-1), f.apply(-100)); }
@Override public <U> Array<T> sortBy( Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) { final Function<? super T, ? extends U> domain = Function1.of(mapper::apply).memoized(); return toJavaStream() .sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2))) .collect(collector()); }
private void calibration_market_quote_sensitivity_check( Function<MarketData, ImmutableRatesProvider> calibrator, double shift) { double notional = 100_000_000.0; double fx = 1.1111; double fxPts = 0.0012; FxSwapTrade trade = EUR_USD.toTrade( VAL_DATE, Period.ofWeeks(6), Period.ofMonths(5), BuySell.BUY, notional, fx, fxPts); ImmutableRatesProvider result = CALIBRATOR.calibrate(CURVE_GROUP_CONFIG, VAL_DATE, ALL_QUOTES, TS); PointSensitivities pts = FX_PRICER.presentValueSensitivity(trade.getProduct(), result); CurveCurrencyParameterSensitivities ps = result.curveParameterSensitivity(pts); CurveCurrencyParameterSensitivities mqs = MQC.sensitivity(ps, result); double pvUsd = FX_PRICER.presentValue(trade.getProduct(), result).getAmount(USD).getAmount(); double pvEur = FX_PRICER.presentValue(trade.getProduct(), result).getAmount(EUR).getAmount(); double[] mqsUsd1Computed = mqs.getSensitivity(USD_DSCON_CURVE_NAME, USD).getSensitivity().toArray(); for (int i = 0; i < USD_DSC_NB_NODES; i++) { Map<MarketDataKey<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues()); map.put( QuoteKey.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[i])), USD_DSC_MARKET_QUOTES[i] + shift); ImmutableMarketData marketData = ImmutableMarketData.of(map); ImmutableRatesProvider rpShifted = calibrator.apply(marketData); double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(USD).getAmount(); assertEquals(mqsUsd1Computed[i], (pvS - pvUsd) / shift, TOLERANCE_PV_DELTA); } double[] mqsUsd2Computed = mqs.getSensitivity(USD_DSCON_CURVE_NAME, EUR).getSensitivity().toArray(); for (int i = 0; i < USD_DSC_NB_NODES; i++) { Map<MarketDataKey<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues()); map.put( QuoteKey.of(StandardId.of(SCHEME, USD_DSC_ID_VALUE[i])), USD_DSC_MARKET_QUOTES[i] + shift); ImmutableMarketData ov = ImmutableMarketData.of(map); ImmutableRatesProvider rpShifted = calibrator.apply(ov); double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(EUR).getAmount(); assertEquals(mqsUsd2Computed[i], (pvS - pvEur) / shift, TOLERANCE_PV_DELTA); } double[] mqsEur1Computed = mqs.getSensitivity(EUR_DSC_CURVE_NAME, USD).getSensitivity().toArray(); for (int i = 0; i < EUR_DSC_NB_NODES; i++) { assertEquals(mqsEur1Computed[i], 0.0, TOLERANCE_PV_DELTA); } double[] mqsEur2Computed = mqs.getSensitivity(EUR_DSC_CURVE_NAME, EUR).getSensitivity().toArray(); for (int i = 0; i < EUR_DSC_NB_NODES; i++) { Map<MarketDataKey<?>, Object> map = new HashMap<>(ALL_QUOTES.getValues()); map.put( QuoteKey.of(StandardId.of(SCHEME, EUR_DSC_ID_VALUE[i])), EUR_DSC_MARKET_QUOTES[i] + shift); ImmutableMarketData marketData = ImmutableMarketData.of(map); ImmutableRatesProvider rpShifted = calibrator.apply(marketData); double pvS = FX_PRICER.presentValue(trade.getProduct(), rpShifted).getAmount(EUR).getAmount(); assertEquals(mqsEur2Computed[i], (pvS - pvEur) / shift, TOLERANCE_PV_DELTA, "Node " + i); } }
/** * Tests the performance of an event listener on the map for Update events of 2 MB strings. Expect * it to handle at least 50 2 MB updates per second. */ @Test public void testSubscriptionMapEventListenerUpdatePerformance() { _testMap.clear(); // Put values before testing as we want to ignore the insert events Function<Integer, Object> putFunction = a -> _testMap.put(TestUtils.getKey(_mapName, a), _twoMbTestString); IntStream.range(0, _noOfPuts) .forEach( i -> { putFunction.apply(i); }); Jvm.pause(100); // Create subscriber and register TestChronicleMapEventListener mapEventListener = new TestChronicleMapEventListener(_mapName, _twoMbTestStringLength); Subscriber<MapEvent> mapEventSubscriber = e -> e.apply(mapEventListener); clientAssetTree.registerSubscriber( _mapName + "?bootstrap=false", MapEvent.class, mapEventSubscriber); KVSSubscription subscription = (KVSSubscription) serverAssetTree.getAsset(_mapName).subscription(false); waitFor(() -> subscription.entrySubscriberCount() == 1); Assert.assertEquals(1, subscription.entrySubscriberCount()); // Perform test a number of times to allow the JVM to warm up, but verify runtime against // average TestUtils.runMultipleTimesAndVerifyAvgRuntime( i -> { if (i > 0) { waitFor(() -> mapEventListener.getNoOfUpdateEvents().get() >= _noOfPuts); // Test that the correct number of events were triggered on event listener Assert.assertEquals(_noOfPuts, mapEventListener.getNoOfUpdateEvents().get()); } Assert.assertEquals(0, mapEventListener.getNoOfInsertEvents().get()); Assert.assertEquals(0, mapEventListener.getNoOfRemoveEvents().get()); mapEventListener.resetCounters(); }, () -> { IntStream.range(0, _noOfPuts) .forEach( i -> { putFunction.apply(i); }); }, _noOfRunsToAverage, 3 * _secondInNanos); clientAssetTree.unregisterSubscriber(_mapName, mapEventSubscriber); waitFor(() -> subscription.entrySubscriberCount() == 0); Assert.assertEquals(0, subscription.entrySubscriberCount()); }
@Test public void chunkFromString() { Function<Node, ContentChunk> chunkGenerator = FileContentReplace.chunkFromString("Test chunk."); Node ourNode = new NodeImpl(new RevisionImpl(2)); ourNode.getHeaders().put(NodeHeader.ACTION, "add"); ourNode.getHeaders().put(NodeHeader.PATH, "/somepath/is/here.txt"); assertThat(new String(chunkGenerator.apply(ourNode).getContent()), is(equalTo("Test chunk."))); }
@Override public TestProperty replaceValue( TestProperty value, Function<String, String> replacementFunction) { return new TestProperty( value .getConfiguration() .clone( replacementFunction.apply(value.getConfiguration().getName()), replacementFunction), replacementFunction.apply(value.getValue())); }
public static void main(String[] args) { Predicate<Object> condition = Objects::isNull; Function<Object, Integer> ifTrue = obj -> 0; Function<CharSequence, Integer> ifFalse = CharSequence::length; Function<String, Integer> safeStringLength = ternaryOperator(condition, ifTrue, ifFalse); System.out.println(safeStringLength.apply("1234")); System.out.println(safeStringLength.apply("")); System.out.println(safeStringLength.apply(null)); }
private void traceDone(final T value) { _shallowTraceBuilder.setResultType(ResultType.SUCCESS); final Function<T, String> traceValueProvider = _traceValueProvider; if (traceValueProvider != null) { try { _shallowTraceBuilder.setValue(traceValueProvider.apply(value)); } catch (Exception e) { _shallowTraceBuilder.setValue(Exceptions.failureToString(e)); } } }
/** * Uso da interface funcional java.util.consumer.Function<T, R> método principal: R apply(T t); */ public static void exampleOfFunction() { BigDecimal notFormatted = BigDecimal.valueOf(3.141592653); Function<BigDecimal, String> f = (BigDecimal param) -> { param = param.setScale(2, BigDecimal.ROUND_HALF_EVEN); return param.toString(); }; print(f.apply(notFormatted)); }
@SuppressWarnings("unchecked") @Override public Function<Object[], ?> visit(UnaryExpression e) { final Function<Object[], ?> first = e.getFirst().accept(this); switch (e.getExpressionType()) { case ExpressionType.ArrayLength: return t -> Array.getLength(first.apply(t)); case ExpressionType.BitwiseNot: return (Function<Object[], ?>) bitwiseNot((Function<Object[], Number>) first); case ExpressionType.Convert: final Class<?> to = e.getResultType(); if (to.isPrimitive() || Number.class.isAssignableFrom(to)) return t -> { Object source = first.apply(t); if (source instanceof Number) { Number result = (Number) source; if (to.isPrimitive()) { if (to == Integer.TYPE) return result.intValue(); if (to == Long.TYPE) return result.longValue(); if (to == Float.TYPE) return result.floatValue(); if (to == Double.TYPE) return result.doubleValue(); if (to == Byte.TYPE) return result.byteValue(); if (to == Character.TYPE) return (char) result.intValue(); if (to == Short.TYPE) return result.shortValue(); } else if (result != null) { if (to == BigInteger.class) return BigInteger.valueOf(result.longValue()); if (to == BigDecimal.class) return BigDecimal.valueOf(result.doubleValue()); } } if (source instanceof Character) { if (to == Integer.TYPE) return (int) (char) source; if (to == Long.TYPE) return (long) (char) source; if (to == Float.TYPE) return (float) (char) source; if (to == Double.TYPE) return (double) (char) source; } return to.cast(source); }; return first; case ExpressionType.IsNull: return first.andThen(r -> r == null); case ExpressionType.LogicalNot: return normalize(not((Function<Object[], Boolean>) first)); case ExpressionType.Negate: return (Function<Object[], ?>) negate((Function<Object[], Number>) first); case ExpressionType.Quote: return constant(first); // case ExpressionType.UnaryPlus: // return abs((Function<? extends Number, Object[]>) first); default: throw new IllegalArgumentException(ExpressionType.toString(e.getExpressionType())); } }
public static <T, R> R callMemoized( final BiFunction<Function<T, R>, T, R> function, final T input) { Function<T, R> memoized = new Function<T, R>() { private final Map<T, R> store = new HashMap<>(); public R apply(final T input) { return store.computeIfAbsent(input, key -> function.apply(this, key)); } }; return memoized.apply(input); }
static { // helper functions Function<Bet, String> teamCodeOrDefault = t -> t.getTeam() != null ? t.getTeam().getCode() : "???"; // bi-predicates to use for the checks BiPredicate<Bet, Bet> compatibleSameTeam = (a, b) -> teamCodeOrDefault.apply(a).equals(teamCodeOrDefault.apply(b)); BiPredicate<Bet, Bet> compatibleSameTeamAndTime = compatibleSameTeam.and((a, b) -> a.getTime().equals(b.getTime())); // basic checks for bets of same type only depending on the team MapBuilder<BetType, Map<BetType, BiPredicate<Bet, Bet>>> checks = MapBuilder.first( BetType.TEAM_KICKS_OFF, MapBuilder.single(BetType.TEAM_KICKS_OFF, compatibleSameTeam)) .add( BetType.TEAM_SCORES_FIRST_GOAL, MapBuilder.single(BetType.TEAM_SCORES_FIRST_GOAL, compatibleSameTeam)) .add( BetType.TEAM_AWARDED_FIRST_THROW_IN, MapBuilder.single(BetType.TEAM_AWARDED_FIRST_THROW_IN, compatibleSameTeam)); checks // checks for bets of different types representing end states only depending on the team .add( BetType.TEAM_WINS, MapBuilder.first(BetType.TEAM_WINS, compatibleSameTeam) .add(BetType.TEAM_WINS_LEADING_WITH_NOF_GOALS, compatibleSameTeam) .last(BetType.ENDS_TIED, compatibleSameTeam)) .add( BetType.TEAM_WINS_LEADING_WITH_NOF_GOALS, MapBuilder.first(BetType.TEAM_WINS_LEADING_WITH_NOF_GOALS, compatibleSameTeam) .last(BetType.ENDS_TIED, compatibleSameTeam)) .add(BetType.ENDS_TIED, MapBuilder.single(BetType.ENDS_TIED, compatibleSameTeam)); COMPATIBLE_CHECKS = checks // advanced checks for bets of different types representing intermediary states // depending on the team and time .add( BetType.TEAM_LEADS_AFTER_TIME, MapBuilder.first(BetType.TEAM_LEADS_AFTER_TIME, compatibleSameTeamAndTime) .add(BetType.TEAM_LEADS_AFTER_TIME_WITH_NOF_GOALS, compatibleSameTeamAndTime) .last(BetType.TIED_AFTER_TIME, compatibleSameTeamAndTime)) .add( BetType.TEAM_LEADS_AFTER_TIME_WITH_NOF_GOALS, MapBuilder.first( BetType.TEAM_LEADS_AFTER_TIME_WITH_NOF_GOALS, compatibleSameTeamAndTime) .last(BetType.TIED_AFTER_TIME, compatibleSameTeamAndTime)) .last( BetType.TIED_AFTER_TIME, MapBuilder.single(BetType.TIED_AFTER_TIME, compatibleSameTeamAndTime)); }
private static BiFunction<String[], Function<Context, Player>, Placeholder> ofIntFunction( Function<Player, Integer> function) { return (tokens, playerFunction) -> { if (tokens.length == 0) { return new PlayerBoundPlaceholder( playerFunction, player -> function.apply(player).toString()); } else { String format = "%0" + tokens[0] + "d"; return new PlayerBoundPlaceholder( playerFunction, player -> String.format(format, function.apply(player))); } }; }
@Override public <K2, V2> TreeMap<K2, V2> bimap( Comparator<? super K2> keyComparator, Function<? super K, ? extends K2> keyMapper, Function<? super V, ? extends V2> valueMapper) { Objects.requireNonNull(keyMapper, "keyMapper is null"); Objects.requireNonNull(valueMapper, "valueMapper is null"); return createTreeMap( new EntryComparator<>(keyComparator), entries .iterator() .map(entry -> Tuple.of(keyMapper.apply(entry._1), valueMapper.apply(entry._2)))); }
@Override public OutputStream pipe(String command, PrintStream out, PrintStream err) { CommandInvocation invocation = javaArgs.parse(command, JAVA_OPTIONS.separatorCode(' ')); Matcher identifierMatcher = lambdaIdentifierRegex.matcher(invocation.getUnprocessedInput()); if (identifierMatcher.matches()) { String lambdaArgIdentifier = identifierMatcher.group("id"); String lambdaBody = identifierMatcher.group("body").trim(); if (lambdaBody.endsWith(";")) { lambdaBody = lambdaBody.substring(0, lambdaBody.length() - 1); } String lineConsumerCode = "return (java.util.function.Function<String, ?>)" + "((" + lambdaArgIdentifier.trim() + ") -> " + lambdaBody + ")"; JavaCode functionCode = new JavaCode(code); functionCode.addLine(lineConsumerCode); Optional<Callable<?>> callable = javacService.compileJavaSnippet(functionCode, classLoaderContext, err); if (callable.isPresent()) { try { Function<String, ?> callback = (Function<String, ?>) callable.get().call(); return new LineOutputStream( line -> { @Nullable Object output = callback.apply(line); if (output != null) { out.println(output); } }, out); } catch (Exception e) { err.println(e); } } } throw new RuntimeException( "When used in a pipeline, the Java snippet must be in the form of a " + "lambda of type Function<String, ?> that takes one text line of the input at a time.\n" + "Example: ... | java line -> line.contains(\"text\") ? line : null"); }