New Features of Java 8 & mdash; Lambdas expression, javalambdas

Source: Internet
Author: User

New Features of Java 8 -- Lambdas expression, javalambdas
Content

  • Introduction
  • Test Data
  • Collect (toList ())
  • Map
  • Filter
  • FlatMap
  • Max and min
  • Reduce
  • Integrated Operation
  • References

Java 8's improvements to core class libraries mainly include collection class APIs and newly introduced streams ). Streaming allows programmers to operate collections at a higher abstraction level.

Download Demo Introduction

Suppose there is a collection of artists, which will be defined later (the artist includes attributes such as name, song, and nationality. The following code calculates the number of artists from UK:

int count = 0;
for (Artist artist : allArtists) {
    if (artist.isFrom("UK")) {
        count++;
    }
}

Simple and standard writing is nothing more than traversing it. If it comes from UK, the count is increased by 1.This is imperative programming, which contains a lot of sample code. The sample code blur the Code's intent and cannot express the programmer's intent smoothly. In general, the for Loop will confuse the behavior with the method. In my opinion, the behavior is higher than the abstract level of the method. An action can be composed of multiple methods. That is to say, an action may be completed by multiple methods.

A for Loop is actually a syntactic sugar that encapsulates iteration. The following code is used:

int count = 0;
Iterator<Artist> iterator = allArtists.iterator();
while (iterator.hasNext()) {
    Artist artist = iterator.next();
    if (artist.isFrom("UK")) {
        count++;
    }
}

In any case, the above method cannot achieve the abstract purpose, nor can the process express the intent, and is essentially a serialized operation.

The following code uses the Java 8 new feature Stream to implement the above functions:

long count = allArtists.stream().filter(artist -> artist.isFrom("UK")).count();

Can clearly express the intent; if you want to Parallel, you can call the Parallel method on Stream and then perform subsequent operations.

The whole process is divided into two simpler operations: filtering and counting, which seem to be simplified to a complex one. It seems that two cycles are executed, but in fact, the design of the class library is more subtle, you only need to iterate on the artist set once.

This is also the idea of functional programming. If a name list is given, some have only one character. You must use commas (,) as the delimiter and return the name in the list. A string does not contain a single letter, and each name has an uppercase letter. Code is easy to write. The key lies in the idea.In essence, three tasks are executed: filter, list to remove single characters, convert the first letter of each name in the list to uppercase, and then convert the list to a string. In imperative languages, you have to use the same low-level mechanism for all three tasks (iterate over the list ). Functional Languages treat filtering, transformation, and conversion as common operations, so they provide you with solutions to problems from different perspectives.

Scala uses industry-specific names for filtering, transformation, and conversion concepts, namely filter, map, and reduce. You will see similar class libraries in the next Java 8.

Test Data

For more information about the definition of the Track, Album, and Artist classes, see the Demo. As you can imagine, assume that you have a CD. Album is the Album, which is the CD. An Album contains multiple music, and a Track is each music, which contains the music name and duration; artist is the Artist of Zhang CD. He may be an individual or a team.

package com.example.java8lambdas.data;
 
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
 
import com.example.java8lambdas.base.Album;
import com.example.java8lambdas.base.Artist;
import com.example.java8lambdas.base.Track;
 
import static java.util.Arrays.asList;
 
public class SampleData {
 
    public static final Artist johnColtrane = new Artist("John Coltrane", "US");
    public static final Artist johnLennon = new Artist("John Lennon", "UK");
    public static final Artist paulMcCartney = new Artist("Paul McCartney", "UK");
    public static final Artist georgeHarrison = new Artist("George Harrison", "UK");
    public static final Artist ringoStarr = new Artist("Ringo Starr", "UK");
 
    public static final List<Artist> membersOfTheBeatles = Arrays.asList(johnLennon, paulMcCartney, georgeHarrison,
            ringoStarr);
    public static final Artist theBeatles = new Artist("The Beatles", membersOfTheBeatles, "UK");
 
    public static final Album aLoveSupreme = new Album("A Love Supreme",
            asList(new Track("Acknowledgement", 467), new Track("Resolution", 442)), asList(johnColtrane));
 
    public static final Album sampleShortAlbum = new Album("sample Short Album", asList(new Track("short track", 30)),
            asList(johnColtrane));
 
    public static final Album manyTrackAlbum = new Album(
            "sample Short Album", asList(new Track("short track", 30), new Track("short track 2", 30),
                    new Track("short track 3", 30), new Track("short track 4", 30), new Track("short track 5", 30)),
            asList(johnColtrane));
 
    public static Stream<Album> albums = Stream.of(aLoveSupreme);
 
    public static Stream<Artist> threeArtists() {
        return Stream.of(johnColtrane, johnLennon, theBeatles);
    }
 
    public static List<Artist> getThreeArtists() {
        return Arrays.asList(johnColtrane, johnLennon, theBeatles);
    }
 
    public static List<Album> getAlbum() {
        return Arrays.asList(aLoveSupreme, sampleShortAlbum, manyTrackAlbum);
    }
}
Collect (toList ())

A list is generated by the values in Stream, which is an early evaluation operation. Many Stream operations are inert evaluation. Therefore, after calling a series of methods on Stream, you need to call an early evaluation method similar to collect.

In the so-called, the inert evaluate method does not generate a new set of methods, most Stream methods are inert evaluate; the method for generating values from Stream such as count is to evaluate values as early as possible. To determine whether an operation is an inert evaluation or an early evaluation, you only need to check its return value. If the returned value is Stream, it is the inertia evaluation; otherwise, it is the early evaluation.

Stream.of(johnColtrane, johnLennon, theBeatles).collect(toList())
Turn the three artists into a List <Artist> set. Map

Convert one type of value to another type, that is, convert the value in a stream into a new stream. If there is a List <Artist> List artists

List<String> collects = artists.stream().map(artist -> artist.getName()).collect(toList());

Returns the names of all artists. Note that a string list is returned. Artists have many attributes, but all I need is their names.

Java 8 introduces the concept of method reference. Therefore, the above Code can also be written in the form of "Class Name: Method:

artists.stream().map(Artist::getName).collect(toList());

Map, ing, and data type conversion can also be completed. For example, the following code converts the string to uppercase, converts the string to an integer, and converts the hexadecimal format to decimal:

List<String> strArr = Stream.of("a", "b", "c").map(s -> s.toUpperCase()).collect(toList());
Assert.assertEquals(Arrays.asList("A", "B", "C"), strArr);
 
List<Integer> iArr = Stream.of("1", "2", "3").map(s -> Integer.valueOf(s)).collect(toList());
Assert.assertEquals(Arrays.asList(1, 2, 3), iArr);
 
List<Integer> iArr2 = Stream.of("0A", "0B", "0C").map(s -> Integer.valueOf(s, 16)).collect(toList());
Assert.assertEquals(Arrays.asList(10, 11, 12), iArr2);
Filter

Traverse and check the elements. Some elements in Stream are retained, and other elements are filtered out. If there is a List <Artist> List artists

List<Artist> collect = artists.stream().filter(artist -> "UK".equals(artist.getNationality())).collect(toList());

Returns the list of artists whose nationality is UK.

FlatMap

You can use Stream to replace values. Multiple Streams are connected to one Stream. If there are two Artist lists <Artist> artists1 and artists2

List<Artist> collect = Stream.of(artists1, artists2).flatMap(numbers -> numbers.stream()).collect(toList());

Returns a set of two artist lists.

Max and min

Calculate the maximum and minimum values. If there are three songs

List<Track> tracks = Arrays.asList(new Track("Bakai", 524), new Track("Violets for Your Furs", 378),
        new Track("Time Was", 541));
Track shortestTrack = tracks.stream().min(Comparator.comparing(track -> track.getLength())).get();

Returns the music with the minimum length.

Reduce

To generate a value from a group of values. The count, min, and max methods of Stream are actually reduce operations. Accumulate as follows:

int sum = Stream.of(1, 2, 3).reduce(0, (acc, element) -> acc + element);
Integrated Operation

Next, let's look at another example. Suppose we can find out the nationality of all the bands on an album. The problem can be broken down into the following steps:

Set<String> collect = album.getMusicians().filter(artist -> artist.getName().startsWith("The"))
        .map(artist -> artist.getNationality()).collect(toSet());
  

Note:

  • The artist list contains both individuals and bands, and can be considered to start with The band ".
  • The getMusicians method of the Album class returns the Stream object. This shows that the exposure Stream Set may be better than the exposure List or Set object. Its biggest advantage is that it encapsulates the internal data structure. No matter how you use it in actual operations, it does not affect the internal List or Set.
References
  • Java finally has a Lambda expression ~ Java 8 language changes-Lambda expressions and Interface Class Changes
  • Next-generation Java: Functional encoding styles-functions shared by Groovy, Scala, and Clojure and their advantages

 

Download Demo

Related Article

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.