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

The following are Jave code examples for showing how to use apply() of the java.util.function.Function class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: vertx-zero   File: Pond.java   View Source Code Vote up 6 votes
/**
 * Zipper
 *
 * @param object
 * @param <K>
 * @param <V>
 * @param <E>
 * @return
 */
static <K, V, E> ConcurrentMap<K, V> zipper(
        final Collection<E> object,
        final Function<E, K> keyFn,
        final Function<E, V> valueFn
) {
    final ConcurrentMap<K, V> ret = new ConcurrentHashMap<>();
    if (0 < object.size()) {
        for (final E item : object) {
            if (null != item) {
                final K key = keyFn.apply(item);
                final V value = valueFn.apply(item);
                if (null != key && null != value) {
                    ret.put(key, value);
                }
            }
        }
    }
    return ret;
}
 
Example 2
Project: gradle-initializr   File: DefaultGradleInitializrService.java   View Source Code Vote up 6 votes
private byte[] createDownloadFile(Function<File, File> action) {
    Path tmpDir = null;

    try {
        tmpDir = createTempDir();

        if (logger.isDebugEnabled()) {
            logger.debug("Generating project in temporary directory " + tmpDir.toFile());
        }

        File download = action.apply(tmpDir.toFile());
        return fileToByteArray(download);
    } catch(Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpDir != null) {
            if (!FileSystemUtils.deleteRecursively(tmpDir.toFile())) {
                logger.warn("Unable to delete temporary directory " + tmpDir.toFile());
            }
        }
    }
}
 
Example 3
Project: syndesis   File: DataManager.java   View Source Code Vote up 6 votes
@SafeVarargs
public final <T extends WithId<T>> ListResult<T> fetchAll(Class<T> model, Function<ListResult<T>, ListResult<T>>... operators) {

    ListResult<T> result;
    if (getDataAccessObject(model) != null) {
        result = doWithDataAccessObject(model, d -> d.fetchAll());
    } else {
        Kind kind = Kind.from(model);
        Map<String, T> cache = caches.getCache(kind.getModelName());
        result = ListResult.of(cache.values());
    }

    if (operators == null) {
        return result;
    }

    for (Function<ListResult<T>, ListResult<T>> operator : operators) {
        result = operator.apply(result);
    }
    return result;
}
 
Example 4
Project: ytk-learn   File: DataUtils.java   View Source Code Vote up 5 votes
public static <T, R> void travel(Function<T, R> func, List<Iterator<T>> iterators) {
    for (Iterator<T> it : iterators) {
        while(it.hasNext()) {
            func.apply(it.next());
        }
    }

}
 
Example 5
Project: springmock   File: ApplicationContextWalker.java   View Source Code Vote up 5 votes
private <T> Collection<T> walkContext(Function<ApplicationContext, T> contextProcessor) {
	final List<T> result = new LinkedList<>();
	ApplicationContext currentContext = applicationContext;
	while (currentContext != null) {
		T processingResult = contextProcessor.apply(currentContext);
		currentContext = currentContext.getParent();

		result.add(processingResult);
	}

	return result;
}
 
Example 6
Project: ARCLib   File: Utils.java   View Source Code Vote up 5 votes
public static <T extends Enum> LabeledReference toLabeledReference(T obj, Function<T, String> nameMapper) {
    if (obj != null) {
        return new LabeledReference(obj.toString(), nameMapper.apply(obj));
    } else {
        return null;
    }
}
 
Example 7
Project: dais   File: IInterceptor.java   View Source Code Vote up 5 votes
static Map<Object,Object> leave(IInterceptor interceptor, Map<Object,Object> context) {
    Function<Map<Object,Object>,Map<Object,Object>> lFn = (interceptor != null) ? interceptor.getLeave() : null;
    if (lFn != null) {
        return lFn.apply(context);
    } else {
        return context;
    }
}
 
Example 8
Project: Java-9-Cookbook   File: Chapter04Functional.java   View Source Code Vote up 5 votes
private static Supplier<String> applyCompareAndSay(int i, Function<Integer, Double> func, Predicate<Double> compare, String message){
    Supplier<String> supplier = new Supplier<String>() {
        public String get() {
            double v = func.apply(i);
            return (compare.test(v)? v + " is " : v + " is not ") + message;
        }
    };
    return supplier;
}
 
Example 9
Project: incubator-netbeans   File: ModuleOraculum.java   View Source Code Vote up 5 votes
@CheckForNull
private String computeModuleIfAbsent(
        @NonNull FileObject root,
        @NonNull final Function<FileObject,String> provider) {
    final Pair<Pair<Reference<FileObject>,File>,String> entry = modNameCache.get();
    FileObject owner;
    String modName;
    if (entry == null ||
            (owner = entry.first().first().get()) == null ||
            !owner.equals(root)) {
        modName = provider.apply(root);
        final File modInfo = Optional.ofNullable(FileUtil.toFile(root))
                .map((rf) -> new File(rf, String.format("%s.%s", FileObjects.MODULE_INFO, FileObjects.JAVA)))   //NOI18N
                .orElse(null);
        final Pair<Pair<Reference<FileObject>,File>,String> newEntry = Pair.of(
                Pair.of(new WeakReference<>(root), modInfo),
                modName);
        if (modNameCache.compareAndSet(entry, newEntry)) {
            if (entry != null && entry.first().second() != null) {
                FileUtil.removeFileChangeListener(this, entry.first().second());
            }
            if (newEntry.first().second() != null) {
                FileUtil.addFileChangeListener(this, newEntry.first().second());
            }
        }
        LOG.log(Level.FINE, "modNameCache updated: {0}", modName);  //NOI18N
    } else {
        modName = entry.second();
    }
    return modName;
}
 
Example 10
Project: Windmill   File: ExcelCell.java   View Source Code Vote up 5 votes
private<T> T tryGetValue(Function<Double, T> cast) {
	if (excelCell != null) {
		if (excelCell.getCellTypeEnum() == CellType.FORMULA) {
			excelCell.setCellType(CellType.NUMERIC);
		}
		if(excelCell.getCellTypeEnum() == CellType.NUMERIC) {
			return cast.apply(excelCell.getNumericCellValue());
		}
	}
	return null;
}
 
Example 11
Project: Java-9-with-JShell   File: example12_03.java   View Source Code Vote up 5 votes
public List<Integer> filterNumbersWithFunction(final List<Integer> numbers,
    Function<Integer, Boolean> function) {
    List<Integer> filteredNumbers = new ArrayList<>();
    for (Integer number : numbers) {
        if (function.apply(number)) {
            filteredNumbers.add(number);
        }
    }
    return filteredNumbers; 
}
 
Example 12
Project: Spring-5.0-Cookbook   File: EmployeeDataService.java   View Source Code Vote up 4 votes
public Date convertBday(long bdayLong){
	Function<Long, Date> bday = Date::new;
	return bday.apply(bdayLong);
}
 
Example 13
Project: redis-cluster-watchdog   File: Tuple1.java   View Source Code Vote up 4 votes
public <V1> Tuple1<V1> map(Function<Tuple1<T1>, Tuple1<V1>> function) {
    return function.apply(this);
}
 
Example 14
Project: samza-sql-tools   File: GenerateKafkaEvents.java   View Source Code Vote up 4 votes
private static void generateEvents(String brokers, String topicName, String eventType, long numEvents)
    throws UnsupportedEncodingException, InterruptedException {
  Properties props = new Properties();
  props.put("bootstrap.servers", brokers);
  props.put("retries", 100);
  props.put("batch.size", 16384);
  props.put("key.serializer", ByteArraySerializer.class.getCanonicalName());
  props.put("value.serializer", ByteArraySerializer.class.getCanonicalName());

  Function<Integer, Pair<String, byte[]>> eventGenerator;
  if (eventType.toLowerCase().contains(PAGEVIEW_EVENTTYPE)) {
    eventGenerator = GenerateKafkaEvents::generatePageViewEvent;
  } else {
    eventGenerator = GenerateKafkaEvents::generateProfileChangeEvent;
  }

  boolean doSleep = false;
  // sleep only when the events have to be produced continuously.
  if (numEvents == Long.MAX_VALUE) {
    doSleep = true;
  }

  try (Producer<byte[], byte[]> producer = new KafkaProducer<>(props)) {
    for (int index = 0; index < numEvents; index++) {
      final int finalIndex = 0;
      Pair<String, byte[]> record = eventGenerator.apply(index);
      producer.send(new ProducerRecord<>(topicName, record.getLeft().getBytes("UTF-8"), record.getRight()),
          (metadata, exception) -> {
            if (exception == null) {
              LOG.info("send completed for event {} at offset {}", finalIndex, metadata.offset());
            } else {
              throw new RuntimeException("Failed to send message.", exception);
            }
          });
      System.out.println(String.format("Published event %d to topic %s", index, topicName));
      if (doSleep) {
        Thread.sleep(1000);
      }
    }

    producer.flush();
  }
}
 
Example 15
Project: Lagerta   File: TripleFunction.java   View Source Code Vote up 4 votes
default <V> TripleFunction<A, B, C, V> andThen(Function<? super R, ? extends V> after) {
    Objects.requireNonNull(after);
    return (a, b, c) -> after.apply(apply(a, b, c));
}
 
Example 16
Project: de.flapdoodle.solid   File: Maybe.java   View Source Code Vote up 4 votes
@Override
public <D> Maybe<D> flatMap(Function<T, Maybe<D>> map) {
	return map.apply(get());
}
 
Example 17
Project: INFSEN01-2   File: Some.java   View Source Code Vote up 4 votes
@Override
public <U> U visit(Supplier<U> onNone, Function<T, U> onSome) {
    return onSome.apply(this.value);
}
 
Example 18
Project: Spring-5.0-Cookbook   File: GenericReferences.java   View Source Code Vote up 4 votes
public int convertInt(String strVal){
	
	Function<String,Integer> convertToInt =  Integer::parseInt;
	return convertToInt.apply(strVal);
}
 
Example 19
Project: aws-sdk-java-v2   File: RequestPipelineBuilder.java   View Source Code Vote up 2 votes
/**
 * Factory method to chain the current {@link RequestPipelineBuilder} with another pipeline stage. The new stage's input type
 * must match the current stage's output type. The new stage may define a new output type (if it's transforming the type) or
 * may define the same output type as the current stage.
 *
 * @param pipelineFactory Factory that can produce a {@link RequestPipeline}. Should take an {@link HttpClientDependencies}
 *                        object as the first parameter to the factory method.
 * @param <NewOutputT>    New output type of pipeline
 * @return A new RequestPipelineBuilder composed of the previous stages and the new stage.
 * @see #build(HttpClientDependencies)
 */
public <NewOutputT> RequestPipelineBuilder<InputT, NewOutputT, D> then(
        Function<D, RequestPipeline<OutputT, NewOutputT>> pipelineFactory) {
    return new RequestPipelineBuilder<>(r -> new ComposingRequestPipelineStage<>(this.pipelineFactory.apply(r),
                                                                                 pipelineFactory.apply(r)));
}
 
Example 20
Project: FreeCol   File: CollectionUtils.java   View Source Code Vote up 2 votes
/**
 * Create a predicate for a type that returns true if a mapper applied
 * to it causes it to equal a key.
 *
 * @param <T> The input type.
 * @param <K> The key type.
 * @param key The key to match.
 * @param mapper The mapper {@code Function} to apply.
 * @return A suitable {@code Predicate}.
 */
public static <T, K> Predicate<T> matchKey(final K key,
                                           Function<T, K> mapper) {
    return t -> mapper.apply(t) == key;
}