Java 8 Lamdba expression 002

Source: Internet
Author: User

Java 8 Lamdba expression 002

This article describes the ordering of lamdba expressions. This example contains a set of Player objects [defined later]. The list player is sorted by the scores of each player. The class definition 001 is as follows:

public class SortingPlayer {public static void main(String[] args) {List
 
   playerList = new ArrayList<>();playerList.add(new Player("Black", "White", 9));playerList.add(new Player("John", "Hello", 2));playerList.add(new Player("Machicel", "Jackson", 7));playerList.add(new Player("Ani", "Hessius", 4));playerList.add(new Player("Mark", "Towns", 3));playerList.add(new Player("Huge", "Nana", 6));}}class Player{private String firstName;private String lastName;private int goals;public Player(String firstName, String lastName, int goals) {this.firstName = firstName;this.lastName = lastName;this.goals = goals;}public String getFirstName() {return firstName;}public void setFirstName(String firstName) {this.firstName = firstName;}public String getLastName() {return lastName;}public void setLastName(String lastName) {this.lastName = lastName;}public int getGoals() {return goals;}public void setGoals(int goals) {this.goals = goals;}}
 
For simplicity, write the code in a class. Player defines firstname, lastname, goals, and Main to create a set and add several elements to it.

The code below 002 is added after the 001main method list

Comparator
 
   byGoals = Comparator.comparing(Player::getGoals);System.out.println("== Sort by Number of Goals ==");playerList.stream().sorted(byGoals).map(p -> p.getFirstName() + " " + p.getLastName() + " - "+ p.getGoals()).forEach(element -> System.out.println(element));
 


Use the getter method of the Player Object to [use goals in this example based on the field you want to sort] to create a Comparator-Player: getGoals. Then, use the hybrid lamdba expression and streams, forEach () to display the sorted set.


Java 8 integrates sorting and adds three new features that can greatly improve development efficiency. They are lamdba expressions, method references, and stream. Method reference and stream are briefly introduced here. Stream can be used in collection data [collections]. It allows the elements in the set to perform function operations. Stream does not store data. It can provide more functions for the collection.

002, Comparator is generated based on the calculated goals, Player: getGoals. Then generate stream based on playerList. Stream provides the sorted () function. It receives a Comparator, which is initialized when it is passed to sorted (), and then calls the map () function. map uses a lamdba expression to spell a firstname, the string of lastname, & goals. Finally, because List It can be iterated and contains the forEach () method. The forEach () method allows each element in the set to apply expressions or status groups. In this example, each element is printed in the command line. Because the map () function has been applied in stream, the final result is to print the firstname, lastname, and, & goals. As follows:

== Sort by Number of Goals ==John Hello - 2Mark Towns - 3Ani Hessius - 4Huge Nana - 6Machicel Jackson - 7Black White - 9


In addition to sorting using the method shown in 002, we can also use the sort () method provided by the Collections set: Collections. sort (), see 003

System.out.println("== utilize the Collections.sort()method ==");Collections.sort(playerList, (p1,p2) -> p1.getLastName().compareTo(p2.getLastName()));playerList.stream().forEach((p) -> {System.out.println(p.getLastName());});
In 003, the first parameter of Collections. sort () is the List of sets to be sorted. The second parameter is the lamdba Implementation of sorting. In this example, the two parameters are both Player objects and their lastname is compared. Therefore, the lastname of the set element is sorted in ascending order. Stream is generated after sorting, and forEach uses the lamdba expression to print the lastname of each element in the sorted set, as shown below:

== utilize the Collections.sort()method ==HelloHessiusJacksonNanaTownsWhite
Undoubtedly, lamdba expressions greatly reduce the Code required for sorting sets. And make the code easier to read. This article is about this. For more features, perform the next decomposition.

Ps: This example is taken from Java 8 Recipes, 2nd Edition by Josh Juneau.

Mission completed!

O (distinct _ distinct) O ~




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.