Java8 new features Learning: Stream and lambda

Source: Internet
Author: User

Streams API

The use of Stream is to implement a filter-map-reduce process that produces a final result, or a side effect (side effect).

There are two types of operations for a stream:

    • Intermediate: A stream can be followed by 0 or more intermediate operations. The main purpose is to open the stream, make a certain degree of data mapping/filtering, and then return a new stream to be used by the next operation. This type of operation is lazy (lazy), which means that only calls to such a method do not actually begin the traversal of the stream.
    • terminal:== a stream can have only one Terminal operation = =, when the operation is executed, the flow is used "light" and can no longer be manipulated. So this must be the last operation of the stream. Terminal the execution of the operation, the traversal of the stream is actually started, and a result is generated, or a side effect.
    • short-circuiting. Used to refer to:
      For a intermediate operation, if it accepts an infinitely large (infinite/unbounded) stream, but returns a limited new stream.
      For a terminal operation, if it accepts an infinitely large Stream, it can calculate the result at a limited time.
      When manipulating an infinitely large Stream and wishing to complete the operation within a limited time, it is necessary to have a short-circuiting operation within the pipeline.
Map/flatmap

Map generates a 1:1 map, and each INPUT element is converted to another element according to the rules. There are a couple of scenarios that are a one-to-many mapping relationship that requires FLATMAP.

Reduce

The main function is to combine the Stream elements. It provides a starting value (seed), followed by an arithmetic rule (binaryoperator), and a combination of the first, second, nth elements of the preceding Stream. In this sense, string concatenation, sum of values, Min, max, average are all special reduce.

Optional

What we can really rely on in Optional is = = = Except for the other methods of IsPresent () and get (): = =

public<U> Optional<U> map(Function<? super T, ? extends U> mapper)public T orElse(T other)public T orElseGet(Supplier<? extends T> other)public void ifPresent(Consumer<? super T> consumer)public Optional<T> filter(Predicate<? super T> predicate)public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X
Construction method

Three ways to construct Optional:

    1. Optional.of (obj),
    2. Optional.ofnullable (obj) and
    3. Clear Optional.empty ()
    • The presence is returned, and none provides the default value
return user.orElse(null);  //而不是 return user.isPresent() ? user.get() : null;return user.orElse(UNKNOWN_USER);
    • The existence is returned, and none is generated by the function.
return user.orElseGet(() -> fetchAUserFromDatabase()); //而不要 return user.isPresent() ? user: fetchAUserFromDatabase();
    • There's nothing to do with it.

      user.isPresent(System.out::println);
    • Map function Grand Debut

When User.ispresent () is true, obtains its associated orders, and returns an empty set for false, we use the above OrElse, the Orelseget method is weak, it is the responsibility of the map function

return user.map(u -> u.getOrders()).orElse(Collections.emptyList())return user.map(u -> u.getUsername())           .map(name -> name.toUpperCase())           .orElse(null);
    • FlatMap

The Flatmap method is similar to the map method, except that the return value of the mapping function is different. The mapping function return value of the map method can be any type T, and the mapping function of the Flatmap method must be optional.

upperName = name.flatMap((value) -> Optional.of(value.toUpperCase()));System.out.println(upperName.orElse("No value found"));//输出SANAULLA
    • Filter

Returns an empty optional if there is a value and the assertion condition is met to return the optional that contains the value.

Optional<String> longName = name.filter((value) -> value.length() > 6);System.out.println(longName.orElse("The name is less than 6 characters"));//输出Sanaulla //另一个例子是Optional值不满足filter指定的条件。Optional<String> anotherName = Optional.of("Sana");Optional<String> shortName = anotherName.filter((value) -> value.length() > 6);//输出:name长度不足6字符System.out.println(shortName.orElse("The name is less than 6 characters"));
Lambda

Use of lambda expressions in Java

While looking very advanced, the essence of the lambda expression is simply a "syntactic sugar" that is inferred by the compiler and helps you transform the wrapper into regular code, so you can use less code to achieve the same functionality.

Suggest not to use, because this and some very high-level hacker write code, simple, difficult to understand, difficult to debug, maintenance personnel want to dozens.

When a developer writes a lambda expression, it is also compiled into a functional interface.

Lambda expressions have a limitation that only final or final local variables can be referenced, which means that variables defined outside the domain cannot be modified inside a lambda.

Lambda表达式的语法基本语法:(params) -> expression(params) -> statement(params) -> { statements }
// 1. 不需要参数,返回值为 5  () -> 5    // 2. 接收一个参数(数字类型),返回其2倍的值  x -> 2 * x    // 3. 接受2个参数(数字),并返回他们的差值  (x, y) -> x – y    // 4. 接收2个int型整数,返回他们的和  (int x, int y) -> x + y    // 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  (String s) -> System.out.print(s)
players.forEach((player) -> System.out.print(player + "; "));     // 在 Java 8 中使用双冒号操作符(double colon operator)  players.forEach(System.out::println);  
// 使用匿名内部类  btn.setOnAction(event -> System.out.println("Hello World!"));  show.addActionListener((e) -> {    System.out.println("Light, Camera, Action !! Lambda expressions Rocks");});
new Thread(() -> System.out.println("Hello world !")).start(); Runnable race2 = () -> System.out.println("Hello world !"); //排序Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));   
  • How to include predicate in a lambda expression

    Predicate<String> startsWithJ = (n) -> n.startsWith("J");Predicate<String> fourLetterLong = (n) -> n.length() == 4;names.stream().filter(startsWithJ.and(fourLetterLong)).forEach((n) -> System.out.print("nName, which starts with ‘J‘ and four letter long is : " + n));
  • Map and reduce examples of using lambda expressions in Java 8

    List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get();
  • Create a string list by filtering

    // 创建一个字符串列表,每个字符串长度大于2List<String> filtered = strList.stream().filter(x -> x.length()> 2).collect(Collectors.toList());System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered);
  • Apply a function to each element of the list

    // 将字符串换成大写并用逗号链接起来List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada");String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));System.out.println(G7Countries);
  • Calculates the maximum, minimum, sum, and average values of a collection element

    //获取数字的个数、最小值、最大值、总和以及平均值List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();System.out.println("Highest prime number in List : " + stats.getMax());System.out.println("Lowest prime number in List : " + stats.getMin());System.out.println("Sum of all prime numbers : " + stats.getSum());System.out.println("Average of all prime numbers : " + stats.getAverage());
Method reference
    • The first method reference is a constructor reference, its syntax is class::new, or the more general class< T >::new.
    • The second method reference is a static method reference, and its syntax is Class::static_method.
    • The third method reference is a method reference to any object of a particular class, and its syntax is Class::method. Please note that this method has no parameters.
String[] stringArray = { "Barbara", "James", "Mary", "John",    "Patricia", "Robert", "Michael", "Linda" };Arrays.sort(stringArray, String::compareToIgnoreCase);The equivalent lambda expression for the method reference String::compareToIgnoreCase would have the formal parameter list (String a, String b), where a and b are arbitrary names used to better describe this example. The method reference would invoke the method a.compareToIgnoreCase(b).public void repair() {           System.out.println( "Repaired " + this.toString() );    }cars.forEach( Car::repair );
    • The fourth method reference is a method reference for a particular object, and its syntax is Instance::method. Note that this method accepts parameters of a car type
class ComparisonProvider {    public int compareByName(Person a, Person b) {        return a.getName().compareTo(b.getName());    }            public int compareByAge(Person a, Person b) {        return a.getBirthday().compareTo(b.getBirthday());    }}ComparisonProvider myComparisonProvider = new ComparisonProvider();Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);final Car police = Car.create( Car::new );cars.forEach( police::follow );public void follow( final Car another ) {        System.out.println( "Following the " + another.toString() );    }
New features of the Java Virtual Machine (JVM)

PermGen space was removed and replaced by Metaspace (JEP 122). The JVM options-xx:permsize and-xx:maxpermsize are replaced by-xx:metaspacesize and-xx:maxmetaspacesize respectively.

Reference
    • Correct posture using the Java8 Optional
    • Java 8 Optional class depth parsing
    • Java8 lambda expression 10 examples
    • Streams API in Java 8
    • The ultimate guide to new features in Java 8

Tips: This article belongs to their own study and practice of the process of recording, many pictures and text are pasted from the online article, no reference please forgive! If you have any questions please leave a message or e-mail notification, I will promptly reply.

Java8 new features Learning: Stream and lambda

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.