Home > Java > javaTutorial > Summary of commonly used built-in functions in java8 (code examples)

Summary of commonly used built-in functions in java8 (code examples)

不言
Release: 2019-03-07 17:50:07
forward
4037 people have browsed it

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

##PredicateTbooleanInput a certain value and output a boolean value, which is used to determine a certain valueConsumerTvoidEnter a certain value, no output. Used to consume a certain value##FunctionSupplierUnaryOperatorBinaryOperatorPredicates
Interface Parameters Return type Description
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();
Copy after login

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, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
 
backToString.apply("123");     // "123"
Copy after login

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
Copy after login

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"));
Copy after login

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);  // < 0
Copy after login

Common methods of Stream

Create Stream

Convert existing data structure into Stream
  1. Stream<Integer> s = Stream.of(1, 2, 3, 4, 5);
    Stream<Integer> s = Arrays.stream(arr);
    Stream<Integer> s = aList.stream();
    Copy after login
    Through Stream .generate() method:
    1. // 这种方法通常表示无限序列
      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;
          }
      }
      Copy after login
    Return through other methods
    1. Stream<String> lines = Files.lines(Path.get(filename))
      ...
      Copy after login
    2. 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, R> {
        // 将T转换为R
        R apply(T t);
    }
    Copy after login

    Usage:
    // 获取Stream里每个数的平方的集合
    Stream<Integer> ns = Stream.of(1, 2, 3, 4, 5);
    ns.map(n -> n * n).forEach(System.out::println);
    Copy after login

    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<Integer>> 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);
    Copy after login

    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);
    }
    Copy after login

    Use
    // 获取当前Stream所有偶数的序列
    Stream<Integer> ns = Stream.of(1, 2, 3, 4, 5);
    ns.filter(n -> n % 2 == 0).forEach(System.out::println);
    Copy after login

    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"));
    Copy after login

    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, T, T> {
        // Bi操作,两个输入,一个输出
        T apply(T t, T u);
    }
    Copy after login

    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);
    Copy after login

    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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template