Java examples for Lambda Stream:Sort
Sorting with Fewer Lines of Code
import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Main { public static void main(String[] args) { List<Player> team = new ArrayList<>(); Player player1 = new Player(); player1.setFirstName("A"); player1.setLastName("AA"); player1.setGoals(5);//from w ww. java 2 s.c om Player player2 = new Player(); player2.setFirstName("B"); player2.setLastName("BB"); player2.setGoals(15); Player player3 = new Player(); player3.setFirstName("C"); player3.setLastName("CC"); player3.setGoals(1); Player player4 = new Player(); player4.setFirstName("D"); player4.setLastName("DD"); player4.setGoals(18); Player player5 = new Player(); player5.setFirstName("E"); player5.setLastName("EE"); player5.setGoals(7); team.add(player1); team.add(player2); team.add(player3); team.add(player4); team.add(player5); Comparator<Player> byGoals = Comparator.comparing(Player::getGoals); List<Player> gteTenGoals = new ArrayList<>(); team.stream() .sorted(byGoals) .map( p -> p.getFirstName() + " " + p.getLastName() + " - " + p.getGoals()).forEach(element -> System.out.println(element)); System.out.println("Number of Players Matching Criteria: " + gteTenGoals.size()); } } class Player { private String firstName = null; private String lastName = null; private String position = null; private int goals; public Player() { } public Player(String position) { this.position = position; } public String playerString() { return getFirstName() + " " + getLastName() + " - " + getPosition(); } /** * @return the firstName */ public String getFirstName() { return firstName; } /** * @param firstName * the firstName to set */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * @return the lastName */ public String getLastName() { return lastName; } /** * @param lastName * the lastName to set */ public void setLastName(String lastName) { this.lastName = lastName; } /** * @return the position */ public String getPosition() { return position; } /** * @param position * the position to set */ public void setPosition(String position) { this.position = position; } /** * @return the goals */ public int getGoals() { return goals; } /** * @param goals * the goals to set */ public void setGoals(int goals) { this.goals = goals; } }