Summary of commonly used built-in functions in java8 (code examples)
This article brings you a summary (code examples) of commonly used built-in functions in Java 8. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Commonly used function interfaces are recorded for easy reference later
Interface | Parameters | Return type | Description |
---|---|---|---|
T | boolean | Input a certain value and output a boolean value, which is used to determine a certain value | |
T | void | Enter a certain value, no output. Used to consume a certain value | |
T | R | Input a certain type of value and output another A type value, used for type conversion, etc. | |
None | T | No input, output a certain Value, used to produce a certain value | |
T | T | Input a certain type of value and output the same Type value, used for same-type conversion of values, such as performing four arithmetic operations on values, etc. | |
(T,T) | T | Input two values of a certain type and output a value of the same type, used for merging two values, etc. |
Predicates is a boolean interface containing one parameter. It includes some default methods, and their combination can implement complex business logic (such as: and, or, negate). The sample code is as follows:
Predicate<string> predicate = (s) -> s.length() > 0; predicate.test("foo"); // true predicate.negate().test("foo"); // false Predicate<boolean> nonNull = Objects::nonNull; Predicate<boolean> isNull = Objects::isNull; Predicate<string> isEmpty = String::isEmpty; Predicate<string> isNotEmpty = isEmpty.negate();</string></string></boolean></boolean></string>
Functions
The Functions interface receives a parameter and produces a result. Its default method is usually used to chain multiple functions together (compose, andThen).
Function<string> toInteger = Integer::valueOf; Function<string> backToString = toInteger.andThen(String::valueOf); backToString.apply("123"); // "123"</string></string>
Suppliers
The Suppliers interface generates a result of a given type. Unlike Functions, it does not receive parameters.
Supplier<person> personSupplier = Person::new; personSupplier.get(); // new Person</person>
Consumers
Consumers represent the execution of an operation with a single input parameter.
Consumer<person> greeter = (p) -> System.out.println("Hello, " + p.firstName); greeter.accept(new Person("Luke", "Skywalker"));</person>
Comparators
Comparators are upgraded from older versions of java and add some default methods.
Comparator<person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // <p> Common methods of Stream</p><h4 id="Create-Stream">Create Stream</h4><h5></h5>Convert existing data structure into Stream<ol><li><pre class="brush:php;toolbar:false">Stream<integer> s = Stream.of(1, 2, 3, 4, 5); Stream<integer> s = Arrays.stream(arr); Stream<integer> s = aList.stream();</integer></integer></integer>Through Stream .generate() method:
// 这种方法通常表示无限序列 Stream<t> s = Stream.generate(SuppLier<t> s); // 创建全体自然数的Stream class NatualSupplier implements Supplier<biginteger> { BigInteger next = BigInteger.ZERO; @Override public BigInteger get() { next = next.add(BigInteger.ONE); return next; } }</biginteger></t></t>
Stream<string> lines = Files.lines(Path.get(filename)) ...</string>
map method
Map an operation operation to a Stream On each element, thereby completing the conversion from one Stream to another Stream
The object accepted by the map method is the Function interface, which is a functional interface:<r> Stream<r> map(Function super T, ? extends R> mapper); @FunctionalInterface public interface Function<t> { // 将T转换为R R apply(T t); }</t></r></r>
Usage:
// 获取Stream里每个数的平方的集合 Stream<integer> ns = Stream.of(1, 2, 3, 4, 5); ns.map(n -> n * n).forEach(System.out::println);</integer>
flatMap
The map method is a one-to-one mapping, and only one value will be output for each input data.
The flatMap method is a one-to-many mapping. Each element is mapped to a Stream, and then the elements of this child Stream are mapped to the parent collection:
Stream<list>> inputStream = Stream.of(Arrays.asList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6)); List<integer> integerList = inputStream.flatMap((childList) -> childList.stream()).collect(Collectors.toList()); //将一个“二维数组”flat为“一维数组” integerList.forEach(System.out::println);</integer></list>
filter method
The filter method is used to filter the elements in the Stream and generate a new Stream with qualified elements.
The parameter accepted by the filter method is the Predicate interface object. This interface is a functional interface:Stream<t> filter(Predicate super T>) predicate; @FunctionInterface public interface Predicate<t> { // 判断元素是否符合条件 boolean test(T t); }</t></t>
Use
// 获取当前Stream所有偶数的序列 Stream<integer> ns = Stream.of(1, 2, 3, 4, 5); ns.filter(n -> n % 2 == 0).forEach(System.out::println);</integer>
limit and skip
limit to limit access The number of results is similar to the limit in the database. Skip is used to exclude the first few results.
sorted
The sorted function needs to pass in an object that implements the Comparator functional interface. The abstract method compare of this interface receives two parameters and returns an integer value. Its function is to sort, and other The common sorting methods are the same.
distinct
distinct is used to eliminate duplicates, which is consistent with the usage of distinct in the database.
findFirst
The findFirst method always returns the first element. If there is no element, it returns empty. Its return value type is Optional. Students who have been exposed to swift should know that this Is an optional type. If there is a first element, the value stored in the Optional type is there. If there is no first element, the type is empty.
Stream<user> stream = users.stream(); Optional<string> userID = stream.filter(User::isVip).sorted((t1, t2) -> t2.getBalance() - t1.getBalance()).limit(3).map(User::getUserID).findFirst(); userID.ifPresent(uid -> System.out.println("Exists"));</string></user>
min, max
min can find the minimum value of the integer stream and return OptionalInt.
max can find the maximum value of the integer stream and return OptionalInt.
These two methods are end operations and can only be called once.
allMatch, anyMatch, noneMatch
allMatch: All elements in the Stream match the incoming predicate and return true
anyMatch: As long as there is one element in the Stream that matches the incoming predicate, it returns true
noneMatch: None of the elements in the Stream matches the incoming predicate and returns true
reduce method
The reduce method applies each element of a Stream to BiFunction at a time, and Combine the results.
The method accepted by the reduce method is the BinaryOperator interface object.Optional<t> reduce(BinaryOperator<t> accumulator); @FuncationalInterface public interface BinaryOperator<t> extends BiFunction<t> { // Bi操作,两个输入,一个输出 T apply(T t, T u); }</t></t></t></t>
Use:
// 求当前Stream累乘的结果 Stream<integer> ns = Stream.of(1, 2, 3, 4, 5); int r = ns.reduce( (x, y) -> x * y ).get(); System.out.println(r);</integer>
The above is the detailed content of Summary of commonly used built-in functions in java8 (code examples). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool