本文整理汇总了Java中java.util.function.Function类的典型用法代码示例。如果您正苦于以下问题:Java Function类的具体用法?Java Function怎么用?Java Function使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Function类属于java.util.function包,在下文中一共展示了Function类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testIntSequentialShortCircuitTerminal
import java.util.function.Function; //导入依赖的package包/类
@Test(groups = { "serialization-hostile" })
public void testIntSequentialShortCircuitTerminal() {
int[] a = new int[]{5, 4, 3, 2, 1};
Function<Integer, IntStream> knownSize = i -> assertNCallsOnly(
Arrays.stream(a).sorted(), (s, c) -> s.peek(c::accept), i);
Function<Integer, IntStream> unknownSize = i -> assertNCallsOnly
(unknownSizeIntStream(a).sorted(), (s, c) -> s.peek(c::accept), i);
// Find
assertEquals(knownSize.apply(1).findFirst(), OptionalInt.of(1));
assertEquals(knownSize.apply(1).findAny(), OptionalInt.of(1));
assertEquals(unknownSize.apply(1).findFirst(), OptionalInt.of(1));
assertEquals(unknownSize.apply(1).findAny(), OptionalInt.of(1));
// Match
assertEquals(knownSize.apply(2).anyMatch(i -> i == 2), true);
assertEquals(knownSize.apply(2).noneMatch(i -> i == 2), false);
assertEquals(knownSize.apply(2).allMatch(i -> i == 2), false);
assertEquals(unknownSize.apply(2).anyMatch(i -> i == 2), true);
assertEquals(unknownSize.apply(2).noneMatch(i -> i == 2), false);
assertEquals(unknownSize.apply(2).allMatch(i -> i == 2), false);
}
示例2: validationDoesNotOccurWhenNoInstantIsProvided
import java.util.function.Function; //导入依赖的package包/类
@Test
public void validationDoesNotOccurWhenNoInstantIsProvided() {
Messages messages = messages();
Function<Object, Instant> instantProvider = context -> null;
IssueInstantValidator<Object> validator = new IssueInstantValidator<>(
TTL_MESSAGE,
INSTANT_IN_FUTURE_MESSAGE,
instantProvider,
TTL,
CLOCK_DELTA
);
Messages returnedMessages = validator.validate(new Object(), messages);
assertThat(returnedMessages, sameInstance(messages));
assertThat(validator.getCondition(), notNullValue());
assertThat(validator.getCondition().test(new Object()), is(false));
assertThat(returnedMessages.hasErrorLike(TTL_MESSAGE), is(false));
assertThat(returnedMessages.hasErrorLike(INSTANT_IN_FUTURE_MESSAGE), is(false));
}
示例3: testFlatMap1
import java.util.function.Function; //导入依赖的package包/类
@Test
public void testFlatMap1() {
ImmutablePerson fred = ImmutablePerson.of("Fred", "Flintstone");
fred = fred.withNickNames("The Fredmeister", "Yabba Dabba Dude");
ImmutablePerson barney = ImmutablePerson.of("Barney", "Rubble");
barney = barney.withNickNames("The Barnster", "Little Buddy");
String expectedAllNickNames = "The Fredmeister,Yabba Dabba Dude,"
+ "The Barnster,Little Buddy";
// (not so good) map each ImmutablePerson to a Stream<String> of nicknames,
// then use flatMap for flatten
String allNickNames = Stream.of(fred, barney) // Stream<ImmutablePerson>
.map(ImmutablePerson::nickNames) // Stream<Stream<String>>
.flatMap(Function.identity()) // Stream<String>
.collect(Collectors.joining(","));
assertThat(allNickNames).isEqualTo(expectedAllNickNames);
}
示例4: shouldWriteReadAny
import java.util.function.Function; //导入依赖的package包/类
@Test
public void shouldWriteReadAny() throws IOException {
OtherRecWithId rec = new OtherRecWithId().setInField(234).setStrField("string456");
RecWithAny r = new RecWithAny().setIntField(123).setStringField("string123").setAnyField(new Any(rec));
byte[] data = BinaryWriter.toBytes(r);
RecWithAny deserializedCustom = BinaryReader.fromBytes(data, RecWithAny.class);
Assert.assertEquals(r, deserializedCustom);
Record deserializedGeneric = BinaryReader.fromBytes(data, RecWithAny.getRecordSchema());
Assert.assertEquals(r, deserializedGeneric);
Assert.assertEquals(rec, deserializedCustom.getAnyField().getCustom((Function) ID_TO_CLZ));
Assert.assertEquals(rec, ((Any) deserializedGeneric.get("anyField")).getGeneric(ID_TO_SCHEMA));
String json = JsonWriter.toString(r);
RecWithAny jsonCustom = JsonReader.fromString(json, RecWithAny.class);
Assert.assertEquals(r, jsonCustom);
Record jsonGen = JsonReader.fromString(json, RecWithAny.getRecordSchema());
Assert.assertEquals(r, jsonGen);
Assert.assertEquals(rec, jsonCustom.getAnyField().getCustom((Function) ID_TO_CLZ));
Assert.assertEquals(rec, ((Any) jsonGen.get("anyField")).getGeneric(ID_TO_SCHEMA));
}
示例5: testDiffableSerialization
import java.util.function.Function; //导入依赖的package包/类
/**
* Tests making random changes to an object, calculating diffs for these changes, sending this
* diffs over the wire and appling these diffs on the other side.
*/
public static <T extends Diffable<T>> void testDiffableSerialization(Supplier<T> testInstance,
Function<T, T> modifier,
NamedWriteableRegistry namedWriteableRegistry,
Reader<T> reader,
Reader<Diff<T>> diffReader) throws IOException {
T remoteInstance = testInstance.get();
T localInstance = assertSerialization(remoteInstance, namedWriteableRegistry, reader);
for (int runs = 0; runs < NUMBER_OF_DIFF_TEST_RUNS; runs++) {
T remoteChanges = modifier.apply(remoteInstance);
Diff<T> remoteDiffs = remoteChanges.diff(remoteInstance);
Diff<T> localDiffs = copyInstance(remoteDiffs, namedWriteableRegistry, diffReader);
localInstance = assertDiffApplication(remoteChanges, localInstance, localDiffs);
remoteInstance = remoteChanges;
}
}
示例6: getSelectionFromList
import java.util.function.Function; //导入依赖的package包/类
/**
* Displays a title for a numbered list of objects and prompts the user to make a selection from that list. Offers
* alternative options.
*
* @param theTitle the title of the list
* @param thePrompt the prompt
* @param theList the list
* @param theToStringFunction a function that maps an object list to a string list
* @param theAlternatives alternative options to the list (e.g. back)
* @return the object selected from the array or null if an alternative option was chosen
* @throws NullPointerException if any parameters are null
*/
protected <E> E getSelectionFromList(final String theTitle, final String thePrompt, final E[] theList,
final Function<E, String> theToStringFunction, final String[] theAlternatives) {
print(Objects.requireNonNull(theTitle));
displayLine();
final Stream<String> listAsStrings = Arrays.stream(Objects.requireNonNull(theList))
.map(Objects.requireNonNull(theToStringFunction));
displayNumberedList(Stream.concat(listAsStrings,
Arrays.stream(Objects.requireNonNull(theAlternatives))).toArray(String[]::new));
displayLine();
final int index = getInteger(Objects.requireNonNull(thePrompt), 1, theList.length + 1);
if (index == theList.length + 1) {
return null;
} else {
return theList[index - 1];
}
}
示例7: noParams
import java.util.function.Function; //导入依赖的package包/类
@Test
public void noParams() {
ListResult<TestPersonInterface> toSort = new ListResult.Builder<TestPersonInterface>().items(getTestData()).totalCount(getTestData().size()).build();
Function<ListResult<TestPersonInterface>, ListResult<TestPersonInterface>> operator =
new ReflectiveSorter<>(TestPersonInterface.class, getOptions(null, null));
ListResult<TestPersonInterface> sorted = operator.apply(toSort);
String[] expectedNames = {
"Schrödinger",
"Heisenberg",
"Feynman",
"Maxwell",
};
for (int i = 0; i < expectedNames.length; i++) {
assertEquals(sorted.getItems().get(i).getLastName(), expectedNames[i]);
}
assertEquals(getTestData().size(), sorted.getTotalCount());
}
示例8: testManyCases
import java.util.function.Function; //导入依赖的package包/类
public static void testManyCases(Function<String, Long> f) {
test("()()()", f);
test("()()?(", f);
test("()()?)", f);
test("()()??", f);
test("(?([?)]?}?", f);
test("(??)", f);
test("????", f);
test("??(?", f);
test("?](?", f);
test("{](?", f);
test("((?)???)()", f);
test("((?)???)?)", f);
test("[(?)???)?)??", f);
test("([{??}])", f);
test("(((((??)))))", f);
test("(((?((??))???)", f);
test("?((?((???]})???)", f);
test("?((?((???]})???)??())?", f);
}
示例9: ConfigPropertyTemplateImpl
import java.util.function.Function; //导入依赖的package包/类
public ConfigPropertyTemplateImpl(ConfigTemplate<?> template, Class<T> rawType, Type genericType, String name, Function<Config, T> defaultValueSupplier,
AnnotatedElement annotatedElement)
{
this.template = template;
this.rawType = rawType;
this.genericType = genericType;
this.defaultValueSupplier = defaultValueSupplier;
this.annotatedElement = annotatedElement;
this.originalName = name;
Comment comment = this.annotatedElement.getAnnotation(Comment.class);
if (this.annotatedElement.isAnnotationPresent(CustomKey.class))
{
this.name = this.annotatedElement.getAnnotation(CustomKey.class).value();
}
else if ((comment != null) && ! comment.name().isEmpty())
{
this.name = comment.name();
}
else
{
this.name = name;
}
}
示例10: splitPackages
import java.util.function.Function; //导入依赖的package包/类
/**
* Returns the list of packages that split between resolved module and
* unnamed module
*/
public Map<String, Set<String>> splitPackages() {
Set<String> splitPkgs = packageToModule.keySet().stream()
.filter(packageToUnnamedModule::containsKey)
.collect(toSet());
if (splitPkgs.isEmpty())
return Collections.emptyMap();
return splitPkgs.stream().collect(toMap(Function.identity(), (pn) -> {
Set<String> sources = new LinkedHashSet<>();
sources.add(packageToModule.get(pn).getModule().location().toString());
packageToUnnamedModule.get(pn).stream()
.map(Archive::getPathName)
.forEach(sources::add);
return sources;
}));
}
示例11: sendRequest
import java.util.function.Function; //导入依赖的package包/类
public <T> T sendRequest (Function <WebClient, T> request) {
int retries = 0;
do {
try {
WebClient webClientCopy = WebClient.fromClient(webClient);
T response = request.apply(webClientCopy);
webClientCopy.close();
return response;
}
catch (NotAuthorizedException e) {
if (retries < 5) {
retries ++;
authClient.refreshAuthenticationContext();
}
else throw e;
}
}
while (retries < 5);
return null;
}
示例12: convertList
import java.util.function.Function; //导入依赖的package包/类
private <T> List<T> convertList(List list) {
if (list.isEmpty()) {
return (List<T>) list;
}
Object elem = list.get(0);
if (!(elem instanceof Map) && !(elem instanceof List)) {
return (List<T>) list;
} else {
Function<Object, T> converter;
if (elem instanceof List) {
converter = object -> (T) new JsonArray((List) object);
} else {
converter = object -> (T) new JsonObject((Map) object);
}
return (List<T>) list.stream().map(converter).collect(Collectors.toList());
}
}
示例13: testToMap
import java.util.function.Function; //导入依赖的package包/类
@Test
public void testToMap(){
List<String> list = Arrays.asList("a2", "bb3", "bb9", "c", "ddd4", "eeee5");
Function<String,String> keyMapper = key -> {
return key.startsWith("e") ? null : key.charAt(0) + "";
};
Function<String,Integer> valueMapper = key -> {
if(key.equals("c")){
return null;
}
char lastChar = key.charAt(key.length() - 1);
return Integer.parseInt(lastChar + "");
};
Map<String,Integer> map = list.stream().collect(CollectorTool.toMap(keyMapper, valueMapper));
Iterator<Entry<String,Integer>> iterator = map.entrySet().iterator();
Assert.assertEquals(nextIn(iterator), "a=2");
Assert.assertEquals(nextIn(iterator), "b=9");
Assert.assertEquals(nextIn(iterator), "c=null");
Assert.assertEquals(nextIn(iterator), "d=4");
Assert.assertEquals(nextIn(iterator), "null=5");
Assert.assertFalse(iterator.hasNext());
}
示例14: testDoubleIteration
import java.util.function.Function; //导入依赖的package包/类
@Test(dataProvider = "Node.Builder<Double>")
public void testDoubleIteration(List<Double> l, Function<Integer, Node.Builder.OfDouble> m) {
Node.Builder.OfDouble nb = m.apply(l.size());
nb.begin(l.size());
for (Double i : l) {
nb.accept((double) i);
}
nb.end();
Node.OfDouble n = nb.build();
assertEquals(n.count(), l.size());
{
List<Double> _l = new ArrayList<>();
n.forEach((DoubleConsumer) _l::add);
assertContents(_l, l);
}
}
示例15: testIntForEachOrdered
import java.util.function.Function; //导入依赖的package包/类
@Test(groups = { "serialization-hostile" })
public void testIntForEachOrdered() {
List<Integer> input = countTo(10000);
TestData.OfInt data = TestData.Factory.ofIntSupplier("[1, 10000]",
() -> IntStream.range(1, 10001));
Function<IntStream, List<Integer>> terminalFunc = s -> {
List<Integer> l = new ArrayList<>();
s.forEachOrdered(l::add);
return l;
};
// Test head
withData(data).
terminal(terminalFunc).
expectedResult(input).
exercise();
// Test multiple stages
withData(data).
terminal(s -> s.map(i -> i), terminalFunc).
expectedResult(input).
exercise();
}