Java examples for Lambda Stream:Sort
Sorting with Collections.sort() method
import java.util.ArrayList; import java.util.Collections; 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 www . ja v a 2 s. co m 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); Collections.sort(team, (p1, p2) -> p1.getLastName().compareTo(p2.getLastName())); List<Player> gteTenGoals = new ArrayList<>(); team.stream().filter(p -> p.getGoals() >= 10).forEach(element -> gteTenGoals.add(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; } }